|
序列化:
public static <T> String serialize(T t) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String jsonResult = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(t);
return jsonResult;
}
反序列化:
public static <T> T deserialize(String string, Class<T> clazz) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(string, clazz);
}
测试
Map<String, String> stringStringMap = new HashMap<String, String>()
stringStringMap.put("key", "value")
System.out.println("serialize = " + serialize(stringStringMap))
System.out.println("deserialize = " + deserialize(serialize(stringStringMap), Map.class))
Map<String, Person> stringPersonMap = new HashMap<String, Person>()
stringPersonMap.put("engineer", Person.builder().firstName("Tom").lastName("Walton").age(19).build())
System.out.println("serialize = " + serialize(stringPersonMap))
System.out.println("deserialize = " + deserialize(serialize(stringPersonMap), Map.class))
Map<Person, Person> personPersonMap = new HashMap<Person, Person>()
personPersonMap.put(Person.builder().firstName("Tom").lastName("Walton").age(19).build(), Person.builder().firstName("Jerry").lastName("Walton").age(59).build())
System.out.println("serialize = " + serialize(personPersonMap))
System.out.println("deserialize = " + deserialize(serialize(personPersonMap), Map.class))
Person person = Person.builder().firstName("FirstName").lastName("LastName").age(19).build()
String strPerson = serialize(person)
System.out.println("serialize =" + strPerson)
System.out.println("deserialize = " + deserialize(strPerson, Person.class))
Person定义
@Builder
@Getter
@Setter
@EqualsAndHashCode
@ToString
@JsonIgnoreProperties
class Person {
@JsonProperty
private String firstName;
@JsonProperty
private String lastName;
@JsonProperty
private int age;
}
http://www.baeldung.com/jackson-map
http://www.baeldung.com/jackson-deserialization |