当前位置: 首页 > 知识库问答 >
问题:

使用Jackson解析JSON文件内容时出现的问题&message-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;
}
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;
}

com.fasterxml.jackson.databind.JSONMappingException:无法反序列化
com.example.geopoint实例,该实例超出了[源:Android.Content.res.AssetManager$AssetInputStream@416a5850;行:5,列:25]
处的START_ARRAY标记(通过引用链:com.example.location[“Center”])

共有1个答案

夏侯俊美
2023-03-14

您的JSON字符串格式不正确:center的类型是一个无效对象数组。将[Latitude周围的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
            }
    }
]
 类似资料: