Json 与 JsonNode 转换

来源:互联网 发布:利用网络赚钱的方法 编辑:程序博客网 时间:2024/04/27 21:44
    import java.io.IOException;      import java.util.Iterator;      import com.fasterxml.jackson.core.JsonParseException;      import com.fasterxml.jackson.databind.JsonMappingException;      import com.fasterxml.jackson.databind.JsonNode;      import com.fasterxml.jackson.databind.ObjectMapper;      public class JacksonTest {          public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {              String json = "{\"username\":\"zhangsan\",\"性别\":\"男\",\"company\":{\"companyName\":\"中华\",\"address\":\"北京\"},\"cars\":[\"奔驰\",\"宝马\"]}";              ObjectMapper mapper = new ObjectMapper();              //JSON ----> JsonNode              JsonNode rootNode = mapper.readTree(json);                Iterator<String> keys = rootNode.fieldNames();                 while(keys.hasNext()){                    String fieldName = keys.next();                    System.out.println(fieldName + ": " + rootNode.path(fieldName).toString());                }              //JsonNode ----> JSON              System.out.println(mapper.writeValueAsString(rootNode));          }      }  
0 0
原创粉丝点击