【发布时间】:2019-01-15 12:27:56
【问题描述】:
我正在尝试显示来自 Web 服务的数据并收到此错误: 线程“main”com.fasterxml.jackson.databind.JsonMappingException 中的异常:无法从 START_OBJECT 令牌中反序列化 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"}
]
}
请帮我检查一下我做错了什么。
谢谢
【问题讨论】:
-
你想先阅读响应然后使用对象映射器吗?同样作为回应,在城镇内部,您需要创建具有公社数组的类,然后使用 parse