Json 与 JsonNode 转换

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

    }  

你可能感兴趣的:(Json 与 JsonNode 转换)