Java JsonMappingException:超出 START_ARRAY 令牌

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19333106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:12:01  来源:igfitidea点击:

JsonMappingException: out of START_ARRAY token

javaarraysjsonHymanson

提问by JJD

Given the following .json file:

鉴于以下 .json 文件:

[
    {
        "name" : "New York",
        "number" : "732921",
        "center" : [
                "latitude" : 38.895111, 
                "longitude" : -77.036667
            ]
    },
    {
        "name" : "San Francisco",
        "number" : "298732",
        "center" : [
                "latitude" : 37.783333, 
                "longitude" : -122.416667
            ]
    }
]

I prepared two classes to represent the contained data:

我准备了两个类来表示包含的数据:

public class Location {
    public String name;
    public int number;
    public GeoPoint center;
}

...

...

public class GeoPoint {
    public double latitude;
    public double longitude;
}

In order to parse the content from the .json file I use Hymanson 2.2.xand prepared the following method:

为了解析 .json 文件中的内容,我使用Hymanson 2.2.x并准备了以下方法:

public static List<Location> getLocations(InputStream inputStream) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        TypeFactory typeFactory = objectMapper.getTypeFactory();
        CollectionType collectionType = typeFactory.constructCollectionType(
                                            List.class, Location.class);
        return objectMapper.readValue(inputStream, collectionType);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

As long as I leave out the centerproperty all content can be parsed. However, when I try to parse the geo-coordinates I end up with the following error message:

只要我省略了center属性,所有内容都可以被解析。但是,当我尝试解析地理坐标时,我最终得到以下错误消息:

com.fasterxml.Hymanson.databind.JsonMappingException: Can not deserialize instance of
com.example.GeoPoint out of START_ARRAY token at [Source: android.content.res.AssetManager$AssetInputStream@416a5850; line: 5, column: 25]
(through reference chain: com.example.Location["center"])

com.fasterxml.Hymanson.databind.JsonMappingException:无法
从 [来源:android.content.res.AssetManager$AssetInputStream@416a5850; 的 START_ARRAY 令牌中反序列化com.example.GeoPoint 的实例;行:5,列:25]
(通过参考链:com.example.Location["center"])

采纳答案by Katona

Your JSON string is malformed: the type of centeris an array of invalid objects. Replace [and ]with {and }in the JSON string around longitudeand latitudeso they will be objects:

您的 JSON 字符串格式错误:类型center是无效对象数组。更换[]使用{,并}在JSON字符串周围longitude,并latitude让他们将对象:

[
    {
        "name" : "New York",
        "number" : "732921",
        "center" : {
                "latitude" : 38.895111, 
                "longitude" : -77.036667
            }
    },
    {
        "name" : "San Francisco",
        "number" : "298732",
        "center" : {
                "latitude" : 37.783333, 
                "longitude" : -122.416667
            }
    }
]

回答by Abhijeet

JsonMappingException: out of START_ARRAY tokenexception is thrown by Hymanson object mapper as it's expecting an Object {}whereas it found an Array [{}]in response.

JsonMappingException: out of START_ARRAY tokenHymanson 对象映射器抛出异常,因为它期待一个Object {}而它发现一个Array [{}]响应。

This can be solved by replacing Objectwith Object[]in the argument for geForObject("url",Object[].class). References:

这可以通过更换得到解决ObjectObject[]在参数geForObject("url",Object[].class)。参考:

  1. Ref.1
  2. Ref.2
  3. Ref.3
  1. 参考文献 1
  2. 参考文献 2
  3. 参考文献 3

回答by freedev

As said, JsonMappingException: out of START_ARRAY tokenexception is thrown by Hymanson object mapper as it's expecting an Object {}whereas it found an Array [{}]in response.

如上所述,JsonMappingException: out of START_ARRAY tokenHymanson 对象映射器抛出异常,因为它期待一个Object {}而它发现一个Array [{}]响应。

A simpler solution could be replacing the method getLocationswith:

一个更简单的解决方案可能是将方法替换为getLocations

public static List<Location> getLocations(InputStream inputStream) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        TypeReference<List<Location>> typeReference = new TypeReference<>() {};
        return objectMapper.readValue(inputStream, typeReference);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

On the other hand, if you don't have a pojo like Location, you could use:

另一方面,如果你没有像 pojo Location,你可以使用:

TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);

回答by Atul Sharma

I sorted this problem as verifying the json from JSONLint.com and then, correcting it. And this is code for the same.

我将此问题归类为从 JSONLint.com 验证 json,然后进行更正。这是相同的代码。

String jsonStr = "[{\r\n" + "\"name\":\"New York\",\r\n" + "\"number\": \"732921\",\r\n"+ "\"center\": {\r\n" + "\"latitude\": 38.895111,\r\n"  + " \"longitude\": -77.036667\r\n" + "}\r\n" + "},\r\n" + " {\r\n"+ "\"name\": \"San Francisco\",\r\n" +\"number\":\"298732\",\r\n"+ "\"center\": {\r\n" + "    \"latitude\": 37.783333,\r\n"+ "\"longitude\": -122.416667\r\n" + "}\r\n" + "}\r\n" + "]";

ObjectMapper mapper = new ObjectMapper();
MyPojo[] jsonObj = mapper.readValue(jsonStr, MyPojo[].class);

for (MyPojo itr : jsonObj) {
    System.out.println("Val of name is: " + itr.getName());
    System.out.println("Val of number is: " + itr.getNumber());
    System.out.println("Val of latitude is: " + 
        itr.getCenter().getLatitude());
    System.out.println("Val of longitude is: " + 
        itr.getCenter().getLongitude() + "\n");
}

Note: MyPojo[].classis the class having getter and setter of json properties.

注意:MyPojo[].class是具有 json 属性的 getter 和 setter 的类。

Result:

结果:

Val of name is: New York
Val of number is: 732921
Val of latitude is: 38.895111
Val of longitude is: -77.036667
Val of name is: San Francisco
Val of number is: 298732
Val of latitude is: 37.783333
Val of longitude is: -122.416667