我有一个预期的 json 文件,如下所示。它是一个嵌套对象
{
"contact_info": [{
"contact_id": "Contact_001",
"contact_status": {
"exam_status": 0,
"term_list": [{
"term_code": 110,
"t_list": [{
"s_code": "12001",
"sexam_status": 0
},
{
"s_code": "13001",
"sexam_status": 1
}
]
}]
}
}]
}
如何将这个对象中所有项的所有字段名和值添加到列表中? 我尝试使用以下方式,但它并不像预期的那样。
//获取json对象中的所有键名
```public static List<String> getAllKeysInJsonUsingJsonNodeFieldNames(String json) {
ObjectMapper mapper = new ObjectMapper()
List<String> keys = new ArrayList<>();
JsonNode jsonNode = mapper.readTree(json);
getAllKeysUsingJsonNodeFields(jsonNode, keys);
return keys;
}
public static void getAllKeysUsingJsonNodeFields(JsonNode jsonNode, List<String> keys) {
if (jsonNode.isObject()) {
Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields();
fields.forEachRemaining({def field ->
keys.add(field.getKey());
getAllKeysUsingJsonNodeFields((JsonNode) field.getValue(), keys);
});
} else if (jsonNode.isArray()) {
ArrayNode arrayField = (ArrayNode) jsonNode;
arrayField.forEach({def node ->
getAllKeysUsingJsonNodeFields(node, keys);
});
}
}```
结果如下 => 只显示字段名,不知道该字段属于哪个对象
标签名[i] = s_code
我希望结果应该在下面,具体来说,我想显示字段名称它属于哪个对象=>你能告诉我如何解决吗?
TagName[i] = contact_status.term_list[0].t_list[0].s_code
抱歉,我是 Java 的新手 => 如果有人知道解决它的方法,请告诉我更多详细信息。非常感谢!
下面的代码使用 jsonNode 将 JSON 对象的字段名称和值添加到 List
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonToListExample {
public static void main(String[] args) throws Exception {
String jsonStr = "{\"contact_info\":[{\"contact_id\":\"Contact_001\",\"contact_status\":{\"exam_status\":0,\"term_list\":[{\"term_code\":110,\"t_list\":[{\"s_code\":12001,\"sexam_status\":0},{\"s_code\":13001,\"sexam_status\":1}]}]}}]}";
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonStr);
List<String> fieldList = new ArrayList<>();
checkFields(rootNode, fieldList);
System.out.println(fieldList);
}
private static void checkFields(JsonNode node, List<String> fieldList) {
Iterator<String> fieldNames = node.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
JsonNode fieldValue = node.get(fieldName);
if (fieldValue.isObject()) {
checkFields(fieldValue, fieldList);
} else if (fieldValue.isArray()) {
for (JsonNode arrayNode : fieldValue) {
checkFields(arrayNode, fieldList);
}
} else {
String fieldStr = fieldName + ": " + fieldValue.toString();
fieldList.add(fieldStr);
}
}
}
}
这段代码做你想要的。
private static String jsonParserTest() {
try {
Map createdMap = new HashMap<String, Object>();
Map<String, Object> tempMap = new HashMap<>();
List<Map> tempList = new ArrayList<>();
tempMap.put("s_code", 12001);
tempMap.put("sexam_status", 0);
tempList.add(tempMap);
tempMap = new HashMap<>();
tempMap.put("s_code", 13001);
tempMap.put("sexam_status", 1);
tempList.add(tempMap);
tempMap = new HashMap<>();
tempMap.put("term_code", 110);
tempMap.put("t_list", tempList);
tempList = new ArrayList<>();
tempList.add(tempMap);
tempList = new ArrayList<>();
tempList.add(tempMap);
tempMap = new HashMap<>();
tempMap.put("exam_status", 0);
tempMap.put("term_list", tempList);
Map<String, Object> tempMap2 = new HashMap<>();
tempMap2.put("contact_status", tempMap);
tempMap2.put("contact_id", "Contact_001");
tempList = new ArrayList<>();
tempList.add(tempMap2);
createdMap.put("contact_info", tempList);
String jsonString = JsonUtils.writeObjectToJsonString(createdMap);
System.out.println(jsonString);
return jsonString;
} catch (IOException e) {
System.out.println(TextUtils.getStacktrace(e));
}
}
返回的字符串是:
{
"contact_info": {
"contact_status": {
"exam_status": 0,
"term_list": [
{
"t_list": [
{
"s_code": 12001,
"sexam_status": 0
},
{
"s_code": 13001,
"sexam_status": 1
}
],
"term_code": 110
}
]
},
"contact_id": "Contact_001"
}
}
而且这个String和你的是同一个Json。基本上,您需要按照您希望 JSON 的外观构建地图,而不仅仅是将其序列化为 Json。在这段代码中,我使用了类
JsonUtils
和TextUtils
。 JsonUtils
类是 Jason-Jackson 库的薄包装器,它使序列化和解析更简单。这些类来自我编写和维护的开源 MgntUtils 库。您可以在 here 或 here 以及 Github 上获取此库作为 Maven 工件,其中包含源代码和 Javadoc。这是JsoonUtils
Javadoc
您可以使用 JSON 库,例如 Josson 来进行转换。
https://github.com/octomix/josson
反序列化
Josson josson = Josson.fromJsonString(
"{" +
" \"contact_info\": [{" +
" \"contact_id\": \"Contact_001\"," +
" \"contact_status\": {" +
" \"exam_status\": 0," +
" \"term_list\": [{" +
" \"term_code\": 110," +
" \"t_list\": [{" +
" \"s_code\": 12001," +
" \"sexam_status\": 0" +
" }," +
" {" +
" \"s_code\": 13001," +
" \"sexam_status\": 1" +
" }" +
" ]" +
" }]" +
" }" +
" }]" +
"}");
查询单独数组中的键和值
Josson flattened = josson.getJosson("contact_info[0].flatten('.','[%d]')");
System.out.println("-- Keys --");
JsonNode node = flattened.getNode("keys()");
List<String> keys = new ArrayList<>();
node.elements().forEachRemaining(elem -> keys.add(elem.asText()));
keys.forEach(System.out::println);
System.out.println("-- Values --");
node = flattened.getNode("toArray()");
List<String> values = new ArrayList<>();
node.elements().forEachRemaining(elem -> values.add(elem.asText()));
values.forEach(System.out::println);
输出
-- Keys --
contact_id
contact_status.exam_status
contact_status.term_list[0].term_code
contact_status.term_list[0].t_list[0].s_code
contact_status.term_list[0].t_list[0].sexam_status
contact_status.term_list[0].t_list[1].s_code
contact_status.term_list[0].t_list[1].sexam_status
-- Values --
Contact_001
0
110
12001
0
13001
1
查询单个数组中的键和值
JsonNode node = josson.getNode("contact_info[0].flatten('.','[%d]').entries().concat(key,' = ',value)");
List<String> keyValues = new ArrayList<>();
node.elements().forEachRemaining(elem -> keyValues.add(elem.asText()));
keyValues.forEach(System.out::println);
输出
contact_id = Contact_001
contact_status.exam_status = 0
contact_status.term_list[0].term_code = 110
contact_status.term_list[0].t_list[0].s_code = 12001
contact_status.term_list[0].t_list[0].sexam_status = 0
contact_status.term_list[0].t_list[1].s_code = 13001
contact_status.term_list[0].t_list[1].sexam_status = 1