JSON使用整数键转换地图 [英] JSON convert Map with Integer keys

查看:155
本文介绍了JSON使用整数键转换地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一小部分测试代码,我尝试将Map转换成JSON字符串并返回。从JSON字符串解析时,生成的映射包含字符串键1而不是整数键1,从而使测试失败。对于用作该地图的关键点的POJO也是一样。这个行为是预期的,还是我没有为JSON转换器配置一些配置?

  public class SampleConverterTest {

@Test
public void testIntegerKey(){

//注册一个整数转换器
JSON.registerConvertor(Integer.class,new JSONPojoConvertor(Integer.class));

地图<整数,字符串> map = new HashMap< Integer,String>();
map.put(1,sample);
//转换为JSON
String msg = JSON.toString(map);
//从JSON获取原始地图
@SuppressWarnings(unchecked)
Map< Integer,String> obj =(Map< Integer,String>)JSON.parse(msg);

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

我正在使用jetty-util 7.6.10.v20130312

解决方案

像@HotLicks所说,当您将对象转换为JSON时,JSON地图的关键部分将返回为String 。我不相信有什么办法可以解决这个问题。如果预期的行为是JSON地图,我也会避开在地图中使用整数作为键。相反,我会做一些类似的事情:

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

这有点更冗长,但是更容易看到如何翻译为JSON。 p>

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

解决方案

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.

这篇关于JSON使用整数键转换地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆