import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
public class JsonTreeModelDemo {
/**
* 获取 JSON 字符串中的 JsonNode
*
* @throws JsonProcessingException
*/
@Test
public void test1() throws JsonProcessingException {
String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 5," +
" \"owners\" : [\"John\", \"Jack\", \"Jill\"]," +
" \"nestedObject\" : { \"field\" : \"value\" } }";
ObjectMapper objectMapper = new ObjectMapper();
// JsonNode jsonNode = objectMapper.readValue(carJson, JsonNode.class);
JsonNode jsonNode = objectMapper.readTree(carJson);
JsonNode brandNode = jsonNode.get("brand");
String brand = brandNode.asText();
System.out.println("brand = " + brand);
JsonNode doorsNode = jsonNode.get("doors");
int doors = doorsNode.asInt();
System.out.println("doors = " + doors);
JsonNode ownersNodeArray = jsonNode.get("owners");
JsonNode owners = ownersNodeArray.get(0);
String john = owners.asText();
String s = ownersNodeArray.toString();
System.out.println(s);
System.out.println("john = " + john);
JsonNode child = jsonNode.get("nestedObject");
JsonNode childField = child.get("field");
String field = childField.asText();
System.out.println("field = " + field);
}
/**
* Java对象转JsonNode
*/
@Test
public void test2() {
ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car();
car.setBrand("Cadillac");
car.setDoors(4);
JsonNode carJsonNode = objectMapper.valueToTree(car);
System.out.println(carJsonNode.toString());
}
/**
* JsonNode转Java对象
*/
@Test
public void test3() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
JsonNode carJsonNode = objectMapper.readTree(carJson);
Car car = objectMapper.treeToValue(carJsonNode, Car.class);
System.out.println(car);
}
}