我在读取此 json 时遇到问题,代码似乎可以工作,但有 2 个问题
- 它只读取 json 的一个 block ,而不是全部。
- 它的属性值始终为“null”。
我一直在尝试显示控制台中组织的 json,但是当我尝试时会发生这两件事。
JSON 数据示例:
{
"RestResponse" : {
"messages" : [ "More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm", "Total [249] records found." ],
"result" : [ {
"name" : "Afghanistan",
"alpha2_code" : "AF",
"alpha3_code" : "AFG"
}, {
"name" : "Åland Islands",
"alpha2_code" : "AX",
"alpha3_code" : "ALA"
}, {
"name" : "Albania",
"alpha2_code" : "AL",
"alpha3_code" : "ALB"
}, ...
]
}
}
我的代码:
public class jsonController {
public void run() {
ObjectMapper mapper = new ObjectMapper();
try {
jsonHandler obj = mapper.readValue(new URL("http://services.groupkt.com/country/get/all"), jsonHandler.class);
//Organized Print
String organizedprint = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
System.out.println(organizedprint);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
我主要有
jsonController obj = new jsonController();
obj.run();
这是 jsonHandler
@JsonIgnoreProperties(ignoreUnknown=true)
public class jsonHandler {
private String restResponse;
private String messages;
private String result;
private String name;
private String alpha2;
private String alpha3;
}
知道我做错了什么吗?
最佳答案
您在模型中声明的数据类型不正确。您的 Java 代码声明数据将有一个包含 6 个字符串属性的对象。服务器提供的JSON数据根本不是这样的。例如,messages
是一个字符串列表,result
是一个对象列表,而不是字符串。您需要相应地声明您的 Java 模型。
例如:
public class jsonHandler
{
private RestResponseStructure restResponse;
}
public class RestResponseStructure
{
private List<String> messages;
private List<CountryRecord> results;
}
public class CountryRecord {
private String name;
private String alpha2_code;
private String alpha3_code;
}
关于java - 使用 Jackson 读取 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41816092/