JSON convert Map with Integer keys

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 11:24:41

问题


I have a small sample of test code where I try to convert a Map into a JSON string and back. While parsing from the JSON string, the resulting map contains the String key "1" instead of the Integer key "1", thus making the test fail. The same happens with POJOs used as the key to this map. Is this behaviour expected or have I ommited some configuration for the JSON converters?

public class SampleConverterTest {

   @Test
   public void testIntegerKey() {

      // Register an Integer converter
      JSON.registerConvertor(Integer.class, new JSONPojoConvertor(Integer.class));

      Map<Integer, String> map = new HashMap<Integer, String>();
      map.put(1, "sample");
      // Convert to JSON
      String msg = JSON.toString(map);
      // Retrieve original map from JSON
      @SuppressWarnings("unchecked")
      Map<Integer, String> obj = (Map<Integer, String>) JSON.parse(msg);

      assertTrue(obj.containsKey(1));
   }
}

I am using jetty-util 7.6.10.v20130312


回答1:


Like @HotLicks said, when you convert objects to JSON, the key part of the JSON map will be returned as a String. I don't believe there's any way to move around this behavior. I'd also steer clear of using integers as keys in your map, if the intended behavior is as a JSON map. Instead, I'd do something like:

map.put("identifier", 1);
map.put("value", "sample");

It's a little bit more verbose, but it's also easier to see how that translates to JSON.



来源:https://stackoverflow.com/questions/19840505/json-convert-map-with-integer-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!