Maven下使用Jackson
1.添加依赖:
2 com.fasterxml.jackson.databind.ObjectMapper在Jackson Databind中。ObjectMapper可以从String,File,InputStream,URL(json数据的格式),自定义的Java类中读取JSON,ObjectMapper中的重载方法readValue()实现了这些功能。下面看从String读取;
public static void readFromString(){
String carJson = "{ \"brand\" : \"Mercedes\"," +
" \"doors\" : 5," +
" \"owners\" : [\"John\", \"Jack\", \"Jill\"]," +
" \"nestedObject\" : { \"field\" : \"value\" } }";
ObjectMapper objectMapper = new ObjectMapper();
try {
// Read JSON from a Reader instance.
// Reader reader = new StringReader(carJson);
// JsonNode node = objectMapper.readValue(reader, JsonNode.class);
JsonNode node = objectMapper.readValue(carJson, JsonNode.class);
JsonNode brandNode = node.get("brand");
String brand = brandNode.asText();
System.out.println("brand = " + brand);
JsonNode doorsNode = node.get("doors");
Integer doors = doorsNode.asInt();
System.out.println("doors = " + doors);
JsonNode owners = node.get("owners");
JsonNode johnNode = owners.get(0);
String owner = johnNode.asText();
System.out.println("john = " + owner);
JsonNode nestNode = node.get("nestedObject");
JsonNode fieldNode = nestNode.get("field");
String field = fieldNode.asText();
System.out.println("field = " + field);
}
catch (Exception e){
e.printStackTrace();
}
}