簡體   English   中英

如何建立一個objectmapper來處理json對象

[英]How to build an objectmapper to handle json objects

我對REST和將json映射到Java Object的整個概念是陌生的。 我知道我需要創建一個類文件,供對象映射器用來創建Java對象。 下面的json是使用resttemplate從WeatherUnderground返回的高端內容。 對我來說,它似乎是對象的數組,而我現在僅對current_observation和display_location對象感興趣。 它似乎也有幾個對象嵌入其他對象中。

我認為我可以弄清楚數組,但是誰能給我一些有關如何映射json對象的指針。

謝謝,羅伯

{
"response": {
"version": "0.1",
"termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"conditions": 1
}
},
"current_observation": {
"image": {
"url": "http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
"title": "Weather Underground",
"link": "http://www.wunderground.com"
},
"display_location": {
"full": "San Francisco, CA",
"city": "San Francisco",
"state": "CA",
"state_name": "California",
"country": "US",
"country_iso3166": "US",
"zip": "94101",
"latitude": "37.77500916",
"longitude": "-122.41825867",
"elevation": "47.00000000"
},

您會發現它實際上非常簡單,我建議使用Jackson 2 ,它具有很多很好的文檔,並且被廣泛使用。

作為樣本的基本用法,我創建了一個Java POJO來將您的響應樣本映射到它。

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Map;    

@JsonIgnoreProperties(ignoreUnknown = true)
public class Response {

    private Map<String, Object> response;


    @JsonProperty("current_observation")
    private Map<String, Object> currentObservation;


    public Map<String, Object> getResponse() {
        return response;
    }

    public void setResponse(Map<String, Object> response) {
        this.response = response;
    }

    public Map<String, Object> getCurrentObservation() {
        return currentObservation;
    }

    public void setCurrentObservation(Map<String, Object> currentObservation) {
        this.currentObservation = currentObservation;
    }
}

然后是一個Test類來測試您的響應並將其綁定到POJO。

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class Test {


    public static void main(String[] args) {

        ObjectMapper objectMapper = new ObjectMapper();


        String responseString = "{\n" +
                                "\"response\": {\n" +
                                "\"version\": \"0.1\",\n" +
                                "\"termsofService\": \"http://www.wunderground.com/weather/api/d/terms.html\",\n" +
                                "\"features\": {\n" +
                                "\"conditions\": 1\n" +
                                "}\n" +
                                "},\n" +
                                "\"current_observation\": {\n" +
                                "\"image\": {\n" +
                                "\"url\": \"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png\",\n" +
                                "\"title\": \"Weather Underground\",\n" +
                                "\"link\": \"http://www.wunderground.com\"\n" +
                                "},\n" +
                                "\"display_location\": {\n" +
                                "\"full\": \"San Francisco, CA\",\n" +
                                "\"city\": \"San Francisco\",\n" +
                                "\"state\": \"CA\",\n" +
                                "\"state_name\": \"California\",\n" +
                                "\"country\": \"US\",\n" +
                                "\"country_iso3166\": \"US\",\n" +
                                "\"zip\": \"94101\",\n" +
                                "\"latitude\": \"37.77500916\",\n" +
                                "\"longitude\": \"-122.41825867\",\n" +
                                "\"elevation\": \"47.00000000\"\n" +
                                "}\n" +
                                "}\n" +
                                "}";

        try {
            Response response = objectMapper.readValue(responseString, Response.class);


            System.out.print("Output: "+ response.getResponse().get("termsofService"));


        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

打印示例響應中的termsOfService的main方法的輸出:

Output: http://www.wunderground.com/weather/api/d/terms.html

希望能幫助到你,

何塞·路易斯

我認為您想讓Json解碼為Object 許多Json庫都支持這種功能。

FastJson為例:

假設您有HelloObject類:

// in HelloObject.java
public class HelloObject
{
    private DisplayLocation display_location;

    // and other members

    // setter and getter
    // ....
}

// in DisplayLocation.java
public class DisplayLocation{

    private String full;
    private String city;

    // and other members

    // setter and getter
    // ...
}

// main
String jsonString = ...;
HelloObject object = JSON.parseObject(jsonString, HelloObject.class);

順便說一下, FastJsonJava最快的JSON庫,比gson更好。

JSON具有內置的數據類型-字符串,布爾值,對象等-因此您只需要根據JSON的規范數據模型來遵循這些數據類型即可。 例如,上面有以下類:

  • 響應
  • 觀察
  • 圖片
  • 位置
  • 條件

再加上一個包裝對象,我們可以將其稱為ResponseWrapper。

在Java中,您需要創建各個類,因此Image類似於

public class Image {
    private String url;
    private String title;
    private String link;

    // getter and setters
}

該屬性的名稱應與JSON的名稱匹配。 但是,如果要使用其他內容,可以使用批注指定。 例如,您可能希望使用displayLocation而不是display_location因此如果您使用的是Jackson,

@JsonProperty("display_location")
private String displayLocation;

然后,在更高級別上匯總這些內容-例如,ResponseWrapper將包含以下內容

public class ResponseWrapper {
    private Response response;
    @JsonProperty("current_observation")
    private CurrentObservation currentObservation;
    // ...and so on
}

暫無
暫無

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

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