1. 程式人生 > >Json 和 JsonNode 區別 和 轉換

Json 和 JsonNode 區別 和 轉換

Json

 String json = "{\"username\":\"zhangsan\",\"性別\":\"男\",\"company\":{\"companyName\":\"微軟\",\"address\":\"美國\"},\"cars\":[\"電車\",\"單車\"]}";  

列印:

{"username":"zhangsan","性別":"男","company":{"companyName":"微軟","address":"美國"},"cars":["電車","單車"]}

JsonNode

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());    
            }

列印:

username: "zhangsan"
性別: "男"
company: {"companyName":"微軟","address":"美國"}
cars: ["電車","單車"]