Jackson基本用法
Talk is cheap. Show me the code.
依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.2</version>
</dependency>
实例
public static void main(String[] args){
ObjectMapper objectMapper = new ObjectMapper();
//序列化
Person p = new Person();
p.setName("jiay");
p.setAge(50);
p.setPosition("山东济南");
try {
String pJson = objectMapper.writeValueAsString(p);
System.out.println("序列化结果:" + pJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//反序列化
String personJson = "{\"name\":\"jiay\",\"age\":\"50\",\"position\":\"xxx\"}";
try {
Person person = objectMapper.readValue(personJson,Person.class);
System.out.println("反序列化结果:" + person.getName() + ":" + person.getAge());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//字符串转JsonNode
try {
JsonNode jsonNode = objectMapper.readTree(personJson);
System.out.println("string2JsonNode结果: name:" + jsonNode.get("name").textValue());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//object转JsonNode
JsonNode jsonNode2 = objectMapper.valueToTree(p);
System.out.println("object2JsonNode结果:name:" + jsonNode2.get("name").textValue());
//JsonNode转object
try {
Person person = objectMapper.treeToValue(jsonNode2,Person.class);
System.out.println("JsonNode2object结果:name:" + person.getName());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//map转JsonNode
Map<String,String> map = new HashMap<>();
map.put("name","jiay");
map.put("age","50");
JsonNode mapNode = objectMapper.valueToTree(map);
System.out.println("map2JsonNode结果:name:" + mapNode.get("name").textValue());
//ArrayList转ArrayNode
List<String> friendList = new ArrayList<>();
friendList.add("jack");
friendList.add("lucy");
ArrayNode arrayNode = objectMapper.valueToTree(friendList);
//ObjectNode
ObjectNode rootNode = objectMapper.createObjectNode();
rootNode.put("name",p.getName());
rootNode.set("friends",arrayNode);
ArrayList<ObjectNode> hobby = new ArrayList<ObjectNode>();
ObjectNode bs = objectMapper.createObjectNode();
bs.put("name","basketball");
hobby.add(bs);
ObjectNode bs2 = objectMapper.createObjectNode();
bs2.put("name","program");
hobby.add(bs2);
rootNode.putArray("hobby").addAll(hobby);
try {
System.out.println("root:" + objectMapper.writeValueAsString(rootNode));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
@Getter
@Setter
static class Person{
private String name;
private int age;
private String position;
public Person(){}
}
结果
欢迎来访
- 有问题欢迎留言或加交流qq:825121848
- 转载请注明出处
- 请小编喝茶~