【问题标题】:How to build an objectmapper to handle json objects如何构建一个objectmapper来处理json对象
【发布时间】:2015-05-07 05:18:27
【问题描述】:

我对 REST 和将 json 映射到 Java 对象的整个概念不熟悉。我知道我需要创建一个对象映射器用来创建 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"
},

【问题讨论】:

  • 如果您对 JSON 到底是什么感兴趣,可以查看here。 REST 和 JSON 是两个完全不同的东西,所以请确保不要将它们混合在一起。首先要注意的是,您提供的是不是有效的 JSON(您可以检查 here)。您的目标是什么并不完全清楚。是从 JSON 获取到您定义的 Java 对象吗?您是否只想使用库解析此 JSON?

标签: java json object


【解决方案1】:

你会发现它其实很简单,我推荐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;
    }
}

然后是一个测试类来测试您的响应并将其绑定到 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

希望对你有帮助,

何塞·路易斯

【讨论】:

    【解决方案2】:

    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
    }
    

    【讨论】:

      【解决方案3】:

      我认为您想让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 好很多。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多