依赖
com.fasterxml.jackson.core jackson-databind ${jackson.version}
public class MyValue {
public String name;
public int age;
}
我们需要一个用于所有数据绑定的实例,所以让我们构造一个:com.fasterxml.jackson.databind.ObjectMapper
ObjectMapper mapper = new ObjectMapper();
MyValue value = mapper.readValue(new File("data.json"), MyValue.class);
// or:
value = mapper.readValue(new URL("http://some.com/api/entry.json"), MyValue.class);
// or:
value = mapper.readValue("{"name":"Bob", "age":13}", MyValue.class);
如果我们想编写JSON,我们反其道而行之:
mapper.writeValue(new File("result.json"), myResultObject);
// or:
byte[] jsonBytes = mapper.writeValueAsBytes(myResultObject);
// or:
String jsonString = mapper.writeValueAsString(myResultObject);
通用的List Map 模型
MapscoreByName = mapper.readValue(jsonSource, Map.class); List names = mapper.readValue(jsonSource, List.class); // and can obviously write out as well mapper.writeValue(new File("names.json"), names);
// can be read as generic JsonNode, if it can be Object or Array; or,
// if known to be Object, as ObjectNode, if array, ArrayNode etc:
ObjectNode root = mapper.readTree("stuff.json");
String name = root.get("name").asText();
int age = root.get("age").asInt();
// can modify as well: this adds child Object as property 'other', set property 'type'
root.with("other").put("type", "student");
String json = mapper.writeValueAsString(root);
// with above, we end up with something like as 'json' String:
// {
// "name" : "Bob", "age" : 13,
// "other" : {
// "type" : "student"
// }
// }



