LinkedHashMap从JSON返回null的get()方法

huangapple go评论79阅读模式
英文:

LinkedHashMap from JSON returns null on get()

问题

我从 JSON 中构建了一个 LinkedHashMap<Byte, Integer>
当我记录这些条目时,它们都在,但是当我调用 get()(例如 40),它返回 null。
我做错了什么?

    String json = "{\"0\":0,\"34\":0,\"36\":0,\"38\":0,\"40\":3}";
    Gson gson = new GsonBuilder().create();
    LinkedHashMap<Byte, Integer> map = new LinkedHashMap<>();
    map = gson.fromJson(json, map.getClass());

    for (Map.Entry<Byte, Integer> entry : map.entrySet()) {
        Log.i(TAG, "item[" + entry.getKey() + "] = " + entry.getValue());
    }
    Log.i(TAG, "map.get(40) = " + map.get(40));

输出:

item[0] = 0.0
item[34] = 0.0
item[36] = 0.0
item[38] = 0.0
item[40] = 3.0
map.get(40) = null
英文:

I build a LinkedHashMap&lt;Byte, Integer&gt; from JSON.
When I log the entries, they are here, but when I call get() (40 for example), it returns null.
Where I'm wrong ?

    String json = &quot;{\&quot;0\&quot;:0,\&quot;34\&quot;:0,\&quot;36\&quot;:0,\&quot;38\&quot;:0,\&quot;40\&quot;:3}&quot;;
    Gson gson = new GsonBuilder().create();
    LinkedHashMap&lt;Byte, Integer&gt; map = new LinkedHashMap&lt;&gt;();
    map = gson.fromJson(json, map.getClass());

    for (Map.Entry&lt;Byte, Integer&gt; entry : map.entrySet()) {
        Log.i(TAG, &quot;item[&quot; + entry.getKey() + &quot;] = &quot; + entry.getValue());
    }
    Log.i(TAG, &quot;map.get(40) = &quot; + map.get(40));

Output :

item[0] = 0.0
item[34] = 0.0
item[36] = 0.0
item[38] = 0.0
item[40] = 3.0
map.get(40) = null

答案1

得分: 1

问题在于密钥的类型不是 Byte,而是 String。仅仅因为你进行了类型转换,并不意味着库会正确地对其进行反序列化,它不关心你声明的 Java 类型,而是关注 fromJson 的第二个参数,该参数在这种情况下只是一个没有泛型的 LinkedHashMap

所以基本上是这样的:map.get("40");

要正确地将其反序列化为 Byte,你可以使用以下代码:

LinkedHashMap<Byte, Integer> map = gson.fromJson(json, TypeToken.getParameterized(LinkedHashMap.class, Byte.class, Integer.class).getType());
System.out.println("map.get(40) = " + map.get((byte) 40));
英文:

Well the problem is that the types of keys are not Byte - they are String. Just because you cast, doesn't mean library will deserialize it correctly, it doesn't look at the java types you declared, but at the second argument to fromJson, which is just a LinkedHashMap with no generics in this case.

So basically: map.get(&quot;40&quot;);.

And to have it correctly deserialized to Byte, you can:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-java -->

LinkedHashMap&lt;Byte, Integer&gt; map = gson.fromJson(json, TypeToken.getParameterized(LinkedHashMap.class, Byte.class, Integer.class).getType());
System.out.println(&quot;map.get(40) = &quot; + map.get((byte)40));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年9月16日 15:01:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63914769.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定