java 使用 GSon 反序列化 Map<Object, Object>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5396578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deserializing Map<Object, Object> with GSon
提问by maaartinus
I have a Map containing a mixture of types like in this simple example
我有一个包含混合类型的 Map,就像这个简单的例子
final Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("a", 1);
map.put("b", "a");
map.put("c", 2);
final Gson gson = new Gson();
final String string = gson.toJson(map);
final Type type = new TypeToken<LinkedHashMap<String, Object>>(){}.getType();
final Map<Object, Object> map2 = gson.fromJson(string, type);
for (final Entry<Object, Object> entry : map2.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
What I get back are plain Object
s, no Integer
s, no String
s. The output looks like
我得到的是普通的Object
s,没有Integer
s,没有String
s。输出看起来像
a : java.lang.Object@48d19bc8
b : java.lang.Object@394a8cd1
c : java.lang.Object@4d630ab9
Can I fix it somehow? I'd expect that such simple cases will be handled correctly by default.
我能以某种方式修复它吗?我希望默认情况下会正确处理这种简单的情况。
I know that the information about the type can't always be preserved, and possibly 1
and "1"
means exactly the same in JSON. However, returning plain content-less objects just makes no sense to me.
我知道无法始终保留有关类型的信息,并且可能1
和"1"
JSON 中的含义完全相同。但是,返回纯内容的对象对我来说毫无意义。
Update:The serialized version (i.e. the string
above) looks fine:
更新:序列化版本(即string
上面的)看起来不错:
{"a":1,"b":"a","c":2}
采纳答案by BalusC
Gson isn't that smart. Rather provide a clear and static data structure in flavor of a Javabean class so that Gson understands what type the separate properties are supposed to be deserialized to.
Gson 没那么聪明。而是提供具有 Javabean 类风格的清晰和静态数据结构,以便 Gson 了解应该将单独的属性反序列化为什么类型。
E.g.
例如
public class Data {
private Integer a;
private String b;
private Integer c;
// ...
}
in combination with
结合
Data data1 = new Data(1, "a", 2);
String json = gson.toJson(data1);
Data data2 = gson.fromJson(json, Data.class);
Update: as per the comments, the keyset seems to be not fixed (although you seem to be able to convert it manually afterwards without knowing the structure beforehand). You could create a custom deserializer. Here's a quick'n'dirty example.
更新:根据评论,键集似乎不是固定的(尽管您似乎可以在事后手动转换它而不事先知道结构)。您可以创建自定义反序列化器。这是一个简单的例子。
public class ObjectDeserializer implements JsonDeserializer<Object> {
@Override
public Object deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException {
String value = element.getAsString();
try {
return Long.valueOf(value);
} catch (NumberFormatException e) {
return value;
}
}
}
which you use as follows:
你使用如下:
final Gson gson = new GsonBuilder().registerTypeAdapter(Object.class, new ObjectDeserializer()).create();
// ...
回答by Michael Lancaster
Gson gson = new GsonBuilder()
.registerTypeAdapter(Object.class, new JsonDeserializer<Object>() {
@Override
public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonPrimitive value = json.getAsJsonPrimitive();
if (value.isBoolean()) {
return value.getAsBoolean();
} else if (value.isNumber()) {
return value.getAsNumber();
} else {
return value.getAsString();
}
}
}).create();
回答by philipjkim
If you want a JSON string from Map<Object, Object>
, I think json-simple
is better choice than Gson
.
如果你想要一个来自 的 JSON 字符串Map<Object, Object>
,我认为json-simple
比Gson
.
This is a brief example from http://code.google.com/p/json-simple/wiki/EncodingExamples:
这是来自http://code.google.com/p/json-simple/wiki/EncodingExamples 的一个简短示例:
//import java.util.LinkedHashMap;
//import java.util.Map;
//import org.json.simple.JSONValue;
Map obj=new LinkedHashMap();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
obj.put("nickname",null);
String jsonText = JSONValue.toJSONString(obj);
System.out.print(jsonText);
Result: {"name":"foo","num":100,"balance":1000.21,"is_vip":true,"nickname":null}
结果: {"name":"foo","num":100,"balance":1000.21,"is_vip":true,"nickname":null}
For decoding, refer to http://code.google.com/p/json-simple/wiki/DecodingExamples.
有关解码,请参阅http://code.google.com/p/json-simple/wiki/DecodingExamples。
回答by John Kane
You are storing the data in a Map. It looks like you need to cast the object to the type you need.
您将数据存储在 Map 中。看起来您需要将对象强制转换为您需要的类型。