簡體   English   中英

使用保留變量將Json轉換為Java對象

[英]Convert Json to Java object using reserved variables

正在具有JSON文件,如下所示

{
      "boost_id": "75149",
      "content_id": "627680",
      "headline": "19 Rare Historical Photos That Will Leave You Breathless ",
      "target_url": "http://stars.americancolumn.com/2016/02/21/historical-photos/?full=1",
      "return": "district" 
 }

我需要將json字符串轉換為java對象。 由於“返回”稱為Java保留關鍵字,因此無法與返回變量一起構成Dto。

還有其他方法可以使用reserve變量並將上述JSON轉換為JAVA對象。

以下是我的Dto結構,

public class RevcontentReportResponse {

    private String boost_id;
    private String content_id;
    private String headline;
    private String target_url;
//  private String return;

    public String getBoost_id() {
        return boost_id;
    }

    public void setBoost_id(String boost_id) {
        this.boost_id = boost_id;
    }

    public String getContent_id() {
        return content_id;
    }

    public void setContent_id(String content_id) {
        this.content_id = content_id;
    }

    public String getHeadline() {
        return headline;
    }

    public void setHeadline(String headline) {
        this.headline = headline;
    }

    public String getTarget_url() {
        return target_url;
    }

    public void setTarget_url(String target_url) {
        this.target_url = target_url;
    }
}

主要方法:

ObjectMapper mapper = new ObjectMapper();

File json = new File("historic.json");
RevcontentReportResponse cricketer = mapper.readValue(json, RevcontentReportResponse.class);
System.out.println("Java object created from JSON String :");
System.out.println(cricketer);

使用JsonProperty批注:

@JsonProperty("return")
private String returnValue;

就是說,JSON代表JavaScript Object Notation,而return也是JavaScript關鍵字(對於許多其他語言來說也是相同的)。 您最好在JSON中更改屬性的名稱。

只需添加一個帶有其getter / setter的字段,然后使用@JsonProperty("return")對其進行注釋@JsonProperty("return")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM