我可能对高级 json/gson 用户有一个简单的问题。我应要求得到如下内容:
[{
"1": {
"2": "6+"
}
},{
"1": []
}]
我尝试使用 gson 将其反序列化为 java 对象,但我遇到了问题。 Gson 向我报告:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line X column Y
如我所见,问题是第一项“1”值被声明为对象,第二项被声明为数组。我对生成的 JSON 没有影响。知道如何正确映射它吗?
也许在 gson 中我可以添加一些钩子(Hook)并且在解析过程中影响应该对项目做什么?例如。当项目“1”的值为“[]”时,则执行与给出具有值的对象时不同的操作?
在 Arkain 评论后我必须添加:
- 在给出的示例中,我们仍然有相同的对象 - 但它的呈现方式不同:/(一次作为空数组 - 另一次作为对象)
根据分析,我认为 Object 应该表示为 e.g.
public class Example { Map<String, Object> 1 = new Map<String,Object>; ... }
但我不知道为什么当 map 为空时在 JSON 中表示为空数组。
- 我不知道 JSON 集合中的位置数量和特定位置的类型。
最佳答案
为了解决问题,我从那里使用了关于自定义反序列化器的答案: Gson deserialize json with varying value types
我创建了自己的反序列化器类,其中我忽略了数组类型(总是空的,我不需要它们):
public class InternalAttributeDeserializer implements JsonDeserializer<Attributes> {
@Override
public Attributes deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
Attributes attrs = new Attributes();
LinkedTreeMap<String, Object> map = context.deserialize(jsonElement, LinkedTreeMap.class);
for (String key : map.keySet()) {
Object obj = map.get(key);
if (obj instanceof LinkedTreeMap) {
@SuppressWarnings("unchecked")
LinkedTreeMap<String, String> imap = (LinkedTreeMap<String, String>) obj;
for (String ikey : imap.keySet()) {
AttributeInProduct iattr = new AttributeInProduct();
iattr.setPres_id(key);
iattr.setAttribute_id(ikey);
iattr.setValue(imap.get(ikey));
attrs.addAttribute(iattr);
}
}
}
return attrs;
}
关于java - 在 gson 中反序列化混合 json 字符串有什么想法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22593754/