在 V2EX 上看到一个提问,如何把复杂的下面的数据解析出来
{ "hosts": { "baidu.com": "127.0.0.1" }, "servers": [ { "address": "1.2.3.4", "port": 5353, "domains": [ "domain:example.com" ] }, "8.8.8.8", "8.8.4.4", "localhost" ], "clientIp": "1.2.3.4", "tag": "dns_inbound" }
针对这种复杂的 JSON ,com.fasterxml.jackson.core.type.TypeReference
类终于是派上用场了。
都用 jackson 了, 当然是写一个类。
废话不多说,直接上代码
package cn.twle.demo; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.util.List; import java.util.Map; public class MyClass { public static void main(String[] args) { try { ObjectMapper mapper = new ObjectMapper(); TypeReference ref = new TypeReference<Response>(){}; Response res = mapper.readValue(new File("serv.json"), ref); List<Server> servers = res.getServers(); for(Server o : servers) { System.out.println(o.getAddress()); } } catch(Exception e) { e.printStackTrace(); } } } class Server { private String address; private Integer port = 0; private List<String> domains; public Server(){} public Server(String address) { this.address = address; this.port = 0; this.domains = null; } public Server(String address, Integer port,List<String> domains) { this.address = address; this.port = port; this.domains = domains; } public String getAddress() { return this.address;} public Integer getPort() { return this.port;} public List<String> getDomains(){ return this.domains;} public void setAddress(String address) { this.address = address;} public void setPort(Integer port) { this.port = port;} public void setDomains(List<String> domains) { this.domains = domains;} } class Response { private Map<String,String> hosts; private List<Server> servers; private String clientIp; private String tag; public Response(){} public Response(Map<String,String> hosts, List<Server> servers, String clientIp, String tag) { this.hosts = hosts; this.servers = servers; this.clientIp = clientIp; this.tag = tag; } public String getTag() { return this.tag;} public String getClientIp() { return clientIp;} public List<Server> getServers() { return servers;} public Map<String,String> getHosts() { return hosts;} public void setTag(String tag) { this.tag = tag;} public void setClientIp(String clientIp) { this.clientIp = clientIp;} public void setHosts(Map<String,String> hosts) { this.hosts = hosts;} public void setServers(List<Server> servers) { this.servers = servers;} }
目前尚无回复