gpt4 book ai didi

java - 异常 : Can not deserialize instance of java. util.ArrayList 超出 START_OBJECT token

转载 作者:行者123 更新时间:2023-11-29 04:12:32 26 4
gpt4 key购买 nike

我正在尝试显示来自网络服务的数据并收到此错误:线程“main”com.fasterxml.jackson.databind.JsonMappingException 中的异常:无法从 START_OBJECT token 中反序列化 java.util.ArrayList 的实例......

在下面找到我的代码:

模型对象:

public class Commune implements Serializable{

private static final long serialVersionUID = 1L;

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Commune [name=" + name + "]";
}
}

主类:

public class Test {

public static void main(String[] args) throws IOException {

URL url = new URL("https://bj-decoupage-territorial.herokuapp.com/api/v1/towns");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");

if(connection.getResponseCode() != 200){
throw new RuntimeException("Failed : Http code : "+connection.getResponseCode());
}

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String output;

while((output = reader.readLine()) != null){

ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Commune>> mapType = new TypeReference<List<Commune>>() {};
List<Commune> jsonToCommuneList = mapper.readValue(output, mapType);

for(Commune c : jsonToCommuneList) {
System.out.println(c.getName());
}
}
connection.disconnect();
}
}

这是从 url 获取的数据:

{"towns":
[
{"name":"BANIKOARA"},
{"name":"GOGOUNOU"},
{"name":"KANDI"},
{"name":"KARIMAMA"}
]
}

请帮我检查一下我做错了什么。

谢谢

最佳答案

您收到此错误是因为您正在尝试将实际上不是 JSON 数组 的内容反序列化为 Collection

如果您能够将 JSON 更改为仅发送 JSON 数组 格式,它将如下所示:

[
{"name":"BANIKOARA"},
{"name":"GOGOUNOU"},
{"name":"KANDI"},
{"name":"KARIMAMA"}
]

否则,要正确解析它,您还可以创建一个新类来表示您的 JSON 的 town 并使用它进行解析:

public class TownRecords implements Serializable {

private List<Commune> communes;

... getters and setters
}

关于java - 异常 : Can not deserialize instance of java. util.ArrayList 超出 START_OBJECT token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54198875/

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