【问题标题】:Flushing a Hashmap of custom Objects in JSON Format以 JSON 格式刷新自定义对象的 Hashmap
【发布时间】:2014-02-03 10:46:29
【问题描述】:

我有一张这张地图:

HashMap<LatLng,ArrayList<String>> dictionary = new  HashMap<LatLng,ArrayList<String>>() ;

我正在尝试使用这样的杰克逊以 JSON 格式将其刷新到磁盘:

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File(MyApplication.getOfflineData()+"/Dictionary.json"), dictionary);

json 文件是这样写的:

"lat/lng: (39.151783,20.97455)": [
"/mnt/sdcard/Android/data/example.perifereia_hpeirou/files/lala/photos/pic1.nomedia",
"/mnt/sdcard/Android/data/example.perifereia_hpeirou/files/lala/photos/pic2.nomedia",
"/mnt/sdcard/Android/data/example.perifereia_hpeirou/files/lala/photos/pic3.nomedia",
"/mnt/sdcard/Android/data/example.perifereia_hpeirou/files/lala/photos/pic4.nomedia"
]

我认为这是不正确的。我认为“纬度/经度”:不应该存在,我该如何纠正这个? 感谢您的宝贵时间。

【问题讨论】:

  • 你能展示你的 LatLng 课程吗?

标签: java android json jackson


【解决方案1】:

当您使用复杂的 POJO 类作为 Map 中的键时,Jackson 必须使用此类生成属性名称。最简单的实现是使用toString 方法。在JSON 中,我们无法创建复杂的属性名称。对象不能是属性。为了解决您的问题,我建议创建包含 LatLngList&lt;String&gt; 属性的新 POJO 类。见例子:

class Root {

    private LatLng latLng;
    private List<String> values;

    //getters,setters
}

现在,您的JSON 将如下所示:

{
  "latLng" : {
    "lat" : "39.151783",
    "lng" : "20.97455"
  },
  "values" : [ "/mnt/sdcard/Android/data/example.perifereia_hpeirou/files/lala/photos/pic1.nomedia", "/mnt/sdcard/Android/data/example.perifereia_hpeirou/files/lala/photos/pic2.nomedia" ]
}

【讨论】:

    【解决方案2】:

    只需清除 HashMap 的值。

    mapper.writeValue(new File(MyApplication.getOfflineData()+"/Dictionary.json"), dictionary.values())
    

    如果要自定义 LatLng 的表示,或者覆盖 LatLng 的 toString()。

    【讨论】:

    • 不能覆盖它 LatLng 不是我的课,我会尝试前者并回复你
    • 可能将 LatLong 包装在自定义类中,然后覆盖 toString()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多