使用 Jackson 和消息解析 JSON 文件中的内容时出现问题 - JsonMappingException - 无法反序列化为 START_ARRAY 令牌

新手上路,请多包涵

给定以下 .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:无法反序列化实例

com.example.GeoPoint 在 [Source: android.content.res.AssetManager$AssetInputStream@416a5850;行:5,列:25]

(通过引用链:com.example.Location[“center”])

原文由 JJD 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 660
2 个回答

您的 JSON 字符串格式错误: center 的类型是无效对象数组。 Replace [ and ] with { and } in the JSON string around longitude and 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
            }
    }
]

原文由 Katona 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

这可以通过在 Object[] 的参数中将 Object 替换为 geForObject("url",Object[].class) 来解决。参考:

  1. 参考资料 1
  2. 参考文献 2
  3. 参考文献 3

原文由 Abhijeet 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题