Jackson(二) Databind

JavaType To json

@Test
public void Object2Json() throws IOException{
    Person person = new Person();
    person.setId(1);
    person.setUsername("zhangSan");
    person.setPassword("1001");
    person.setAddress(new Address("shanghai", "nanjinglu"));
    person.setHobby(new String[]{"object1", "object2", "object3"});

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    String basePath = this.getClass().getClassLoader().getResource("").getPath().substring(1);
    mapper.writeValue(new FileOutputStream(new File(basePath + "object.json")), person);
}

/**
上面代码执行完毕后,生成的json文件如下
{
  "id" : 1,
  "username" : "zhangSan",
  "password" : "1001",
  "address" : {
    "city" : "shanghai",
    "street" : "nanjinglu"
  },
  "hobby" : [ "object1", "object2", "object3" ]
}
*/
@Test
public void Array2Json() throws IOException {
    Person p1 = new Person();
    p1.setId(1);
    p1.setUsername("zhangSan");
    p1.setPassword("1001");
    p1.setAddress(new Address("shanghai", "hongqiaolu"));
    p1.setHobby(new String[]{"array1", "array2", "array3"});
    Person p2 = new Person();
    p2.setId(2);
    p2.setUsername("liSi");
    p2.setPassword("1002");
    p2.setAddress(new Address("beijing", "kaiquanlu"));
    p2.setHobby(new String[]{"array4", "array5", "array6"});
    Person[] personArray = new Person[]{p1, p2};

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    String basePath = this.getClass().getClassLoader().getResource("").getPath().substring(1);
    mapper.writeValue(new FileOutputStream(new File(basePath + "array.json")), personArray);
}

/**
上面代码执行完毕后,生成的json文件如下
[ {
  "id" : 1,
  "username" : "zhangSan",
  "password" : "1001",
  "address" : {
    "city" : "shanghai",
    "street" : "hongqiaolu"
  },
  "hobby" : [ "array1", "array2", "array3" ]
}, {
  "id" : 2,
  "username" : "liSi",
  "password" : "1002",
  "address" : {
    "city" : "beijing",
    "street" : "kaiquanlu"
  },
  "hobby" : [ "array4", "array5", "array6" ]
} ]
*/
@Test
public void List2Json() throws IOException {
    Person p1 = new Person();
    p1.setId(1);
    p1.setUsername("zhangSan");
    p1.setPassword("1001");
    p1.setAddress(new Address("shanghai", "lujiaziu"));
    p1.setHobby(new String[]{"list1", "list2", "list3"});
    Person p2 = new Person();
    p2.setId(2);
    p2.setUsername("liSi");
    p2.setPassword("1002");
    p2.setAddress(new Address("beijing", "renminglu"));
    p2.setHobby(new String[]{"list4", "list5", "list6"});

    List personList = new ArrayList();
    personList.add(p1);
    personList.add(p2);

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    String basePath = this.getClass().getClassLoader().getResource("").getPath().substring(1);
    mapper.writeValue(new FileOutputStream(new File(basePath + "list.json")), personList);
}

/**
上面代码执行完毕后,生成的json文件如下
[ {
  "id" : 1,
  "username" : "zhangSan",
  "password" : "1001",
  "address" : {
    "city" : "shanghai",
    "street" : "lujiaziu"
  },
  "hobby" : [ "list1", "list2", "list3" ]
}, {
  "id" : 2,
  "username" : "liSi",
  "password" : "1002",
  "address" : {
    "city" : "beijing",
    "street" : "renminglu"
  },
  "hobby" : [ "list4", "list5", "list6" ]
} ]
*/
@Test
public void Map2Json() throws IOException {
    Person p1 = new Person();
    p1.setId(1);
    p1.setUsername("zhangSan");
    p1.setPassword("1001");
    p1.setAddress(new Address("shanghai", "yananlu"));
    p1.setHobby(new String[]{"map1", "map2", "map3"});
    Person p2 = new Person();
    p2.setId(2);
    p2.setUsername("liSi");
    p2.setPassword("1002");
    p2.setAddress(new Address("beijing", "dagulu"));
    p2.setHobby(new String[]{"map4", "map5", "map6"});

    List personList = new ArrayList();
    personList.add(p1);
    personList.add(p2);

    Map<String, Object> personMap = new HashMap<String, Object>();
    personMap.put("total", personList.size());
    personMap.put("data", personList);

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    String basePath = this.getClass().getClassLoader().getResource("").getPath().substring(1);
    mapper.writeValue(new FileOutputStream(new File(basePath + "map.json")), personMap);
}

/**
上面代码执行完毕后,生成的json文件如下
{
  "total" : 2,
  "data" : [ {
    "id" : 1,
    "username" : "zhangSan",
    "password" : "1001",
    "address" : {
      "city" : "shanghai",
      "street" : "yananlu"
    },
    "hobby" : [ "map1", "map2", "map3" ]
  }, {
    "id" : 2,
    "username" : "liSi",
    "password" : "1002",
    "address" : {
      "city" : "beijing",
      "street" : "dagulu"
    },
    "hobby" : [ "map4", "map5", "map6" ]
  } ]
}
*/

json To JavaType

@Test
public void testObject2Java() throws IOException{
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

    InputStream objectJsonIn = this.getClass().getClassLoader().getResourceAsStream("object.json");
    Person person = mapper.readValue(objectJsonIn, Person.class);
    System.out.println(person);
}

@Test
public void testArray2Java() throws IOException{
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

    InputStream arrayJsonIn = this.getClass().getClassLoader().getResourceAsStream("array.json");
    Person[] personArray = mapper.readValue(arrayJsonIn, new TypeReference() {}); 
    for (Person person : personArray) {
        System.out.println(person);
    }
}

@Test
public void testList2Java() throws IOException{
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

    InputStream listJsonIn = this.getClass().getClassLoader().getResourceAsStream("list.json");
    List personList = mapper.readValue(listJsonIn, new TypeReference>() {});   
    for (Person person : personList) {
        System.out.println(person);
    }

}

@Test
public void testMap2Java() throws IOException{
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

    InputStream mapJsonIn = this.getClass().getClassLoader().getResourceAsStream("map.json");
    Map personMap = mapper.readValue(mapJsonIn, 
                                            new TypeReference>(){});

    for (Entry entry : personMap.entrySet()) {
        System.out.println(entry.getKey()+ ":" + entry.getValue());
    }
    /*
     * map的另一种遍历方式
    for (String key : personMap.keySet()) {
        Object value = personMap.get(key);
        System.out.println(key + ":" + value);
    }
    */
}

JavaType To Tree(JsonNode)

@Test
public void testJava2Tree() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    Person person = new Person();
    person.setId(1);
    person.setUsername("zhangSan");
    person.setPassword("1001");
    person.setAddress(new Address("shanghai", "daqianmen"));
    person.setHobby(new String[]{"篮球","足球","乒乓球"});
    //转换Java对象到JsonNode
    JsonNode jsonNode = mapper.valueToTree(person);
    String jsonString = mapper.writeValueAsString(jsonNode);
    System.out.println(jsonString);
    //or
    mapper.writeValue(System.out, jsonNode);
}

/**
以上代码执行后的结果,如下
{
  "id" : 1,
  "username" : "zhangSan",
  "password" : "1001",
  "address" : {
    "city" : "shanghai",
    "street" : "daqianmen"
  },
  "hobby" : [ "篮球", "足球", "乒乓球" ]
}
*/

Tree(JsonNode) To JavaType

@Test
public void testTree2Java() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    ObjectNode objectNode = mapper.createObjectNode();
    objectNode.put("id", 1);
    objectNode.put("username", "WangWu");
    objectNode.put("password", "1001");
    objectNode.putPOJO("address", new Address("shanghai", "nanjinglu"));
    //ObjectNode添加ArrayNode
    objectNode.putArray("hobby").add("吃").add("喝").add("玩").add("乐");

    Person person = mapper.treeToValue(objectNode, Person.class);
    System.out.println(person);
}
/**
以上代码执行完后的结果,如下
Person [id=1, username=WangWu, password=1001, 
address=Address [city=shanghai, street=nanjinglu], hobby=[吃, 喝, 玩, 乐]]
*/

json To Tree(JsonNode)

@Test
public void testObject2Tree() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    InputStream objectIn = this.getClass().getClassLoader().getResourceAsStream("object.json");
    JsonNode root = mapper.readTree(objectIn);

    //JsonNode --> JsonString
    String jsonString = mapper.writeValueAsString(root);
    System.out.println(jsonString);

    //遍历JsonNode
    traversalJsonNode(root);

    //查找JsonNode
    JsonNode jsonNode = root.get("username");
    System.out.println(jsonNode.toString());

    //查找指定字段的JsonNode
    List list1 = root.findValues("password");
    for (JsonNode jn : list1) {
        System.out.println(jn.toString());
    }

    //查找指定字段的父节点的JsonNode
    List list2 = root.findParents("password");
    for (JsonNode jn : list2) {
        System.out.println(jn.toString());
    }
}

@Test
public void testList2Tree() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    InputStream listIn = this.getClass().getClassLoader().getResourceAsStream("list.json");
    JsonNode root = mapper.readTree(listIn);

    traversalJsonNode(root);
}

@Test
public void testMap2Tree() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    InputStream mapIn = this.getClass().getClassLoader().getResourceAsStream("map.json");
    JsonNode root = mapper.readTree(mapIn);

    traversalJsonNode(root);
}

/**
 * 深度遍历指定的JsonNode节点
 * @param root
 */
private void traversalJsonNode(JsonNode root) {
    if(root.isContainerNode()){
        if(root.isArray()){
            Iterator it = root.elements();
            while(it.hasNext()){
                JsonNode jn = it.next();
                if(!jn.isContainerNode()){
                    System.out.println(jn.toString());
                }else{
                    traversalJsonNode(jn);
                }
            }
        }else if(root.isObject()){
            //第一种方法
            Iterator it = root.fieldNames();
            while(it.hasNext()){
                String filedName = it.next();
                JsonNode jn = root.get(filedName);
                if(!jn.isContainerNode()){
                    System.out.println(filedName + ":" + jn.toString());
                }else{
                    traversalJsonNode(jn);
                }
            }
            /*
            //第二种遍历方法
            Iterator> it = root.fields();
            while(it.hasNext()){
                Entry entry = it.next();
                String key = entry.getKey();
                JsonNode jsonNode = entry.getValue();
                if(!jsonNode.isContainerNode()){
                    System.out.println(key+":" + jsonNode.toString());
                }else{
                    traversalJsonNode(jsonNode);
                }
            }
            */
        }
    }
}

Tree(JsonNode) To json

@Test
public void testTree2Json() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    ObjectNode objectNode = mapper.createObjectNode();
    objectNode.put("id", 1);
    objectNode.put("username", "WangWu");
    objectNode.put("password", "1001");
    objectNode.putPOJO("address", new Address("shanghai", "nanjinglu"));
    //ObjectNode添加ArrayNode
    objectNode.putArray("hobby").add("吃").add("喝").add("玩").add("乐");
    String jsonString = mapper.writeValueAsString(objectNode);
    System.out.println(jsonString);

    ArrayNode arrayNode = mapper.createArrayNode();
    arrayNode.add("北京");
    arrayNode.add("上海");
    arrayNode.addPOJO(new Address("beijing", "shanghai"));
    //ArrayNode添加ObjectNode
    arrayNode.addObject().put("username", "wangcai").put("age", "3");
    jsonString = mapper.writeValueAsString(arrayNode);
    System.out.println(jsonString);
}

/**
上面代码执行后的结果,如下
{
  "id" : 1,
  "username" : "WangWu",
  "password" : "1001",
  "address" : {
    "city" : "shanghai",
    "street" : "nanjinglu"
  },
  "hobby" : [ "吃", "喝", "玩", "乐" ]
}
[ "北京", "上海", {
  "city" : "beijing",
  "street" : "shanghai"
}, {
  "username" : "wangcai",
  "age" : "3"
} ]
*/

你可能感兴趣的:(json)