JSON convert Map with Integer keys

2019-05-26 22:07发布

问题:

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.