gpt4 book ai didi

java - 解析 JSON 对象列表

转载 作者:行者123 更新时间:2023-12-02 11:37:00 24 4
gpt4 key购买 nike

接收到以下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>>() {
});

我明白了; 无法从 START_OBJECT token 中反序列化java.util.ArrayList实例

第二种方法:

JSONPayload[] payload = mapper.readValue(obj.getjSONRequest(), JSONPayload[].class);

我明白了; 无法从 START_OBJECT token 中反序列化company.JSONPayload[]实例

最佳答案

这有效。添加 []。我用过

payload = objectMapper.readValue(jsonFile, objectMapper.getTypeFactory().constructCollectionType(List.class, Pojo.class));

用于转换。

应用程序.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 + '\'' +
'}';
}
}

关于java - 解析 JSON 对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48865899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com