例外:无法在

时间:2019-01-15 12:27:57

标签: java json

我正在尝试显示来自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"}
   ]
}

请帮助我检查我做错了什么。

谢谢

2 个答案:

答案 0 :(得分:1)

您收到此错误,是因为您试图将实际上不是JSON Array的内容反序列化为Collection

如果您能够更改JSON以仅发送JSON Array格式,则如下所示:

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

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

public class TownRecords implements Serializable {

    private List<Commune> communes;

    ... getters and setters
}

答案 1 :(得分:0)

您正在尝试反序列化Commune列表,但是在HTTP响应中,您将获得一个对象,该对象包含此类列表,但列表本身不包含。因此,您需要另一个包装器对象来反序列化:

包装

public class Towns implements Serializable {
    private List<Commune> towns;

    public Towns() {}

    public List<Commune> getTowns() {
        return towns;
    }

    public void setTowns(List<Commune> towns) {
        this.towns = towns;
    }

    @Override
    public String toString() {
        return "Towns: " + towns.toString();
    }
}

主应用

    TypeReference<Towns> mapType = new TypeReference<Towns>() {};
    Towns towns = mapper.readValue(output, mapType);
    System.out.println(towns);