用数组反序列化json [英] deserializing json with arrays
问题描述
我使用jackson反序列化一些Json。我正在阅读一个大型的json文档并拔出块并告诉jackson将该块取出并将其反序列化为我在java中创建的对象(实际上有几个对象,因为有嵌套数组)以匹配json。
im using jackson to deserialize some Json. I am reading through a large json document and pulling out blocks and telling jackson to take that block and deserialize it to an object that I created (Actually several objects as there are nested arrays) in java to match the json.
用于反序列化的代码是
fooObject newFoo = mapper.readValue(newNode,fooObject.class);
问题是块中有一个值,有时是哈希值,如
The problem is there is a value in the block that is sometimes a hash such as
addWidgetStrategy={"get":2,"spend":6,"textLabel":"bikes"}
有时数组
addWidgetStrategy=[{"get":1.5,"spend":3,"textLabel":"thursday"},{"get":3,"spend":5,"textLabel":"tuesday"}]
所以在fooObject中我需要处理addWidgetStrategy,它有自己的对象。如果在fooObject中我放了
So in fooObject I need to deal with addWidgetStrategy which has its own object. If in fooObject I put
public addWidgetStrategy addWidgetStrategy;
以上工作直到它试图反序列化数组
The above works until it tried to deserialize an array
如果我把
public List<addWidgetStrategy> addWidgetStrategy;
它仅适用于数组,只需单个哈希就会爆炸
it works just for arrays and blows up when its just a single hash
如何解析相同的Json元素addWidgetStrategy,无论它是数组还是单个哈希?
How can I parse that same Json element addWidgetStrategy regardless if its an array or a single hash?
推荐答案
对于数组,它应该是:
fooObject[] newFoo = mapper.readValue(newNode,fooObject[].class);
你可以这样读:
JsonNode jsonNode = mapper.readTree(json);
if (jsonNode.isArray()) {
fooObject[] newFoo = mapper.readValue(jsonNode,fooObject[].class);
...
} else {
fooObject newFoo = mapper.readValue(jsonNode,fooObject.class);
....
}
这篇关于用数组反序列化json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!