JACKSON 遍历改变节点值
package com.magic.mirro;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.TextNode;
import java.util.Iterator;
import java.util.Map;
/**
* Created by dongqingsong on 2020/10/25.
*/
public class JacksonUtils {
public static void jsonLeaf(JsonNode node)
{
if (node.isObject())
{
Iterator<Map.Entry<String, JsonNode>> it = node.fields();
while (it.hasNext())
{
Map.Entry<String, JsonNode> entry = it.next();
if(entry.getValue() instanceof TextNode
&& entry.getValue().isValueNode()){
TextNode t = (TextNode)entry.getValue();
entry.setValue(new TextNode(t.asText().substring(2)));
}
jsonLeaf(entry.getValue());
}
}
if (node.isArray())
{
Iterator<JsonNode> it = node.iterator();
while (it.hasNext())
{
jsonLeaf(it.next());
}
}
}
public static void main(String[] args)
{
try
{
String json ="{\n" +
" \"employees\": [\n" +
" {\n" +
" \"firstName\": \"Bill\",\n" +
" \"lastName\": \"Gates\"\n" +
" },\n" +
" {\n" +
" \"firstName\": \"George\",\n" +
" \"lastName\": \"Bush\"\n" +
" },\n" +
" {\n" +
" \"firstName\": \"Thomas\",\n" +
" \"lastName\": \"Carter\"\n" +
" }\n" +
" ]\n" +
"}";
ObjectMapper jackson = new ObjectMapper();
JsonNode node = jackson.readTree(json);
jsonLeaf(node);
System.out.println(json.toString());
System.out.println(node.toString());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}