接收以下JSON,完全如下所示。我怎么解析这个pojo?
{"name":"test","value":"8893"},
{"name":"test2","value":"1"},
{"name":"test3","value":"68"},
{"name":"test4","value":"26824212473"}
我尝试解析以下两种方式:
第一种方法:
List<JSONPayload> payload = mapper.readValue(obj.getjSONRequest(), new TypeReference<List<JSONPayload>>() {
});
我得到了; Cannot deserialize instance of
的java.util.ArrayList out of START_OBJECT token
第二种方法:
JSONPayload[] payload = mapper.readValue(obj.getjSONRequest(), JSONPayload[].class);
我得到了; Cannot deserialize instance of
company.JSONPayload [] out of START_OBJECT token
答案 0 :(得分:0)
这很有效。添加 []。我用了
payload = objectMapper.readValue(jsonFile, objectMapper.getTypeFactory().constructCollectionType(List.class, Pojo.class));
进行转换。
App.java
public class App {
public static void main(String[] args) {
String jsonFile = "[{\"name\":\"test\",\"value\":\"8893\"},\n" +
"{\"name\":\"test2\",\"value\":\"1\"},\n" +
"{\"name\":\"test3\",\"value\":\"68\"},\n" +
"{\"name\":\"test4\",\"value\":\"26824212473\"}]";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writerWithDefaultPrettyPrinter();
List<Pojo> payload = null;
try {
payload = objectMapper.readValue(jsonFile, objectMapper.getTypeFactory().constructCollectionType(List.class, Pojo.class));
} catch (IOException e) {
e.printStackTrace();
}
payload.forEach(System.out::println);
}
}
Pojo.java
class Pojo {
private String name;
private String value;
public Pojo() {
super();
}
public Pojo(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "Pojo{" +
"name='" + name + '\'' +
", value='" + value + '\'' +
'}';
}
}