英文:
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<Byte, Integer>
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 = "{\"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));
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("40");
.
And to have it correctly deserialized to Byte
, you can:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-java -->
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));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论