@JsonProperty的使用

jackson的maven依賴java

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
</dependency>

因此引入這一個依賴就能夠了json

@JsonProperty 此註解用於屬性上,做用是把該屬性的名稱序列化爲另一個名稱,如把trueName屬性序列化爲name,@JsonProperty(value="name")。app

import com.fasterxml.jackson.annotation.JsonProperty;

public class Student {

    @JsonProperty(value = "real_name") private String realName;

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    @Override
    public String toString() {
        return "Student{" +
                "realName='" + realName + '\'' +
                '}';
    }
}

測試maven

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        Student student = new Student();
        student.setRealName("zhangsan");
        System.out.println(new ObjectMapper().writeValueAsString(student));
    }
}

結果ide

{"real_name":"zhangsan"}

這裏須要注意的是將對象轉換成json字符串使用的方法是fasterxml.jackson提供的!!工具

若是使用fastjson呢?測試

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.28</version>
</dependency>
import com.alibaba.fastjson.JSON;

public class Main {
    public static void main(String[] args) {
        Student student = new Student();
        student.setRealName("zhangsan");
        System.out.println(JSON.toJSONString(student));
    }
}

結果this

{"realName":"zhangsan"}

能夠看到,@JsonProperty(value = "real_name")沒有生效,爲啥?spa

由於fastjson不認識@JsonProperty註解呀!因此要使用jackson本身的序列化工具方法!code

 --------------------------

@JsonProperty不單單是在序列化的時候有用,反序列化的時候也有用,好比有些接口返回的是json字符串,命名又不是標準的駝峯形式,在映射成對象的時候,將類的屬性上加上@JsonProperty註解,裏面寫上返回的json串對應的名字
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        String jsonStr = "{\"real_name\":\"zhangsan\"}";
        Student student = new ObjectMapper().readValue(jsonStr.getBytes(), Student.class);
        System.out.println(student);
    }
}

結果:

Student{realName='zhangsan'}
相關文章
相關標籤/搜索