【发布时间】:2022-10-13 10:00:50
【问题描述】:
JSON 表示 水果: { “类型”:“甜”, “价值”:“苹果” } 我想执行这样的简洁表示。
水果:“苹果”
【问题讨论】:
-
您使用的是 jackson 还是 gson 库?
-
杰克逊图书馆
JSON 表示 水果: { “类型”:“甜”, “价值”:“苹果” } 我想执行这样的简洁表示。
水果:“苹果”
【问题讨论】:
const data = '{ "fruit": { "type": "sweet", "value": "Apple" }}';
const obj = JSON.parse(data);
for (let key in obj) {
console.log(key, obj[key].value); // "fruit", "Apple"
}
【讨论】:
您需要将字符串解析为 JsonNode,然后遍历节点并替换其值,同时检查非空子节点以避免将单个节点替换为空值。
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
String data =
"{ "id": "123", "type": "fruit", "veritey1": { "type": "Property", "value": "moresweetappler" }, "quantity": { "type": "Property", "value":10 } }";
ObjectMapper mapper = new ObjectMapper();
JsonNode nodes = mapper.readTree(data);
Iterator<Entry<String, JsonNode>> iterator = nodes.fields();
while (iterator.hasNext()) {
Entry<String, JsonNode> node = iterator.next();
if (node.getValue().hasNonNull("value")) {
((ObjectNode) nodes).set(node.getKey(), node.getValue().get("value"));
}
}
System.out.println(nodes.toString());
}
输出:
{"id":"123","type":"fruit","veritey1":"moresweetappler","quantity":10}
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
String data =
"{ "tank": { "type": "Relationship", "object": "id007", "time": "2017-07-29T12:00:04Z", "providedBy": { "type": "Relationship", "object": "id009" } } }";
ObjectMapper mapper = new ObjectMapper();
JsonNode nodes = mapper.readTree(data);
Iterator<Entry<String, JsonNode>> iterator = nodes.fields();
while (iterator.hasNext()) {
Entry<String, JsonNode> node = iterator.next();
reduceJson(node.getValue());
}
System.out.println(nodes.toString());
}
public static void reduceJson(JsonNode node) {
if (node.hasNonNull("type")) {
((ObjectNode) node).remove("type");
}
Iterator<Entry<String, JsonNode>> iterator = node.fields();
while (iterator.hasNext()) {
Entry<String, JsonNode> childnode = iterator.next();
if (childnode.getValue().isObject()) {
reduceJson(node.get(childnode.getKey()));
}
}
}
输出:
{"tank":{"object":"id007","time":"2017-07-29T12:00:04Z","providedBy":{"object":"id009"}}}
【讨论】:
{ "id": "123", "type": "fruit", "veritey1": { "type": "Property", "value": "moresweetappler" }, "quantity": { "type": "Property", "value":10 } }的预期输出