【问题标题】:JSON convert Map with Integer keysJSON 使用整数键转换 Map
【发布时间】:2013-11-19 08:49:43
【问题描述】:

我有一小部分测试代码,我尝试将 Map 转换为 JSON 字符串并返回。从 JSON 字符串解析时,生成的映射包含字符串键“1”而不是整数键“1”,从而使测试失败。用作此映射键的 POJO 也会发生同样的情况。这是预期的行为还是我为 JSON 转换器省略了一些配置?

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));
   }
}

我正在使用 jetty-util 7.6.10.v20130312

【问题讨论】:

  • 根据定义,JSON 键是字符串。
  • JSON 键是 strings 一些 JSON 解析器会接受非标准 JSON,其中可能包括非字符串键,但最好坚持标准
  • 这意味着没有 POJO 也可以用作键,对吗?在使用 Sample.class 作为键的情况下,我希望键被转换为 JSON 字符串,例如 {"class":"test.test.Sample","id":1} 但这不会发生在Map 的情况 --> JSON 字符串。
  • 对于大多数 JSON 库,Map 是解析器将 JSON 转换为的默认实现。因此,从地图生成 JSON 时没有指定类。

标签: java json map integer converter


【解决方案1】:

地图也可以存储为元组/对的数组。

{
  "myMap" : [
    {"key": 1, "value": 42}, 
    {"key": 2, "value": 21}, 
    {"key": 3, "value": 31415}
  ]
}

【讨论】:

    【解决方案2】:

    map&lt;int,int&gt; 似乎没有正确匹配。可以使用派生类 - 像这样:

    struct Int_int_map : map<int, int> {
    
        inline friend void to_json(json &j, Int_int_map const &m) {
            j = json();
            for (auto &key_val : m)
                j[to_string(key_val.first)] = key_val.second;
        }
    
        inline friend void from_json(const json &j, Int_int_map &m) {
            for (auto &key_val : j.get<json::object_t>()) 
                m[std::stoi(key_val.first)] = key_val.second;       
        }
    };
    

    【讨论】:

      【解决方案3】:

      就像@HotLicks 所说,当您将对象转换为 JSON 时,JSON 映射的关键部分将作为字符串返回。我不相信有任何办法可以绕过这种行为。如果预期的行为是 JSON 映射,我也会避免在映射中使用整数作为键。相反,我会这样做:

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

      它有点冗长,但也更容易看出它是如何转换为 JSON 的。

      【讨论】:

      • 感谢 Jason 和其他人澄清 JSON 可以支持什么和不支持什么。
      猜你喜欢
      • 2015-06-03
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 2015-04-30
      • 2017-03-25
      相关资源
      最近更新 更多