当前位置: 首页 > 面试题库 >

JsonMappingException:超出START_ARRAY令牌

皇甫雨华
2023-03-14
问题内容

给定以下.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
            ]
    }
]

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

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

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

为了解析.json文件中的内容,我使用Jackson
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;
}

只要我忽略该center属性,就可以解析所有内容。但是,当我尝试解析地理坐标时,出现以下错误消息:

com.fasterxml.jackson.databind.JsonMappingException:无法
从[START_ARRAY]令牌中反序列化com.example.GeoPoint
实例,网址为[Source:android.content.res.AssetManager$AssetInputStream@416a5850;
行:5,列:25]
(通过参考链:com.example.Location [“ center”])


问题答案:

您的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
            }
    }
]


 类似资料: