我有一个JSON字符串,其中包含如下所示的结构,基本上,我有一个VO链,每个VO还将具有VO列表和VO映射。
样品:
"MessageHeader": {
"type": "new",
"id": 10,
"add_record": "true",
},
"MessageBody": {
"dob_required": false,
"dept_name": "Purchase",
"group": {
"main_group": "main group",
"sub_group": "sub group"
},
"family_info": {
"person1": {
"name": "HisName",
"gender": "male",
"age": "31",
"office_info_present": {
"office_name": "present office",
"office_address": "some address"
"some_other_vo":{
},
},
"office_info_previous": {
"office_name": "old office",
"office_address": "some address"
},
},
"person2": {
"name": "HerName",
"gender": "Female",
"age": "25",
}
},
"active":true
}
我想在键值对中打印每个属性名称及其值。我不想打印VO名称,而只打印结束属性(叶级属性)
像下面的字符串:
类型=新id = 10 add_record = true dob_required = false dept_name =购买main_group =“ main group” sub_group =“ sub group” name = HisName性别=男性年龄= 31 .... name = HerName性别=女性年龄= 25
如何做到这一点?我希望可以使用杰克逊来完成。否则也可以。
最佳答案
最简单的方法可能是使用杰克逊的树模型进行遍历。就像是:
JsonNode root = mapper.readValueAsTree(jsonInput);
Map<String,String> flat = new HashMap<String,String>();
traverse(root, flat);
public void traverse(JsonNode node, Map<String,String> result)
{
Iterator<Map.Entry<String,JsonNode>> it = node.fields();
while (it.hasNext()) {
Map.Entry<String,JsonNode> entry = it.next();
JsonNode n = entry.getValue();
if (n.isObject()) { // if JSON object, traverse recursively
traverse(n);
} else { // if not, just add as String
result.put(entry.getKey(), n.asText());
}
}
}
您会得到一张可以打印的地图。