我是一个有用的助手,可以为您进行文本翻译。以下是需要翻译的内容:
我正在尝试从 Web 服务中显示数据,但出现以下错误:异常在线程 "main" 中:"com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at..."
以下是我的代码:
模型对象:
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"}
]
}
请帮我检查一下我做错了什么。
谢谢