使用Jackson进行序列化和反序列化

序列化:

  public static  String serialize(T t) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        String jsonResult = mapper.writerWithDefaultPrettyPrinter()
                .writeValueAsString(t);
        return jsonResult;
    }

反序列化:

    public static  T deserialize(String string, Class clazz) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(string, clazz);
    }

测试

Map stringStringMap = new HashMap();
        stringStringMap.put("key", "value");
        System.out.println("serialize = " + serialize(stringStringMap));
        System.out.println("deserialize = " + deserialize(serialize(stringStringMap), Map.class));

        Map stringPersonMap = new HashMap();
        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 personPersonMap = new HashMap();
        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

你可能感兴趣的:(Java,Python)