【问题标题】:Convert JSON from Elasticsearch to Java Object将 JSON 从 Elasticsearch 转换为 Java 对象
【发布时间】:2019-06-13 23:35:34
【问题描述】:

gson.fromJson 函数有问题。我从我的 ElasticSearch 中获取 JSON。我可以将正文转换为字符串,但不能将其转换为对象。也许我应该使用 Gson 以外的东西?有人可以帮忙吗? 提前谢谢你。

获取数据和gson.fromJson:

 try {
    Response response = restClient.performRequest(
            "GET",
            "/elasticsearch/posts/car/_search",
            Collections.<String, String>emptyMap(),
            entity1);

    String responseBody = EntityUtils.toString(response.getEntity());
    Gson gson = new Gson();
    DataCar dataCar = gson.fromJson(responseBody, DataCar.class);
    GsonBuilder gsonBuilder = new GsonBuilder();
    DataCar cars = gsonBuilder.create().fromJson(responseBody,DataCar.class);
    ArrayList<Car> carsList = cars.getCars();

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

JSON 文本:

 {
   "took":1,
   "timed_out":false,
   "_shards":{"total":1,"successful":1,"skipped":0,"failed":0},
   "hits":{"total":{"value":6,"relation":"eq"},
   "max_score":1.0,
   "hits": [{"_index":"posts","_type":"car","
    _id":"b9ZirGoByBAZW2S2ADLS","
   _score":1.0,
    "_source":{
      "image_url": "https://examplepicturelink.com/xyz.jpg",
      "brand": "Audi",
      "model": "A8",
      "price": "120000",
      "engine":"5.0",
      "year":"2018",
      "hp":"380",
      "mileage":"100",
      "color":"czarny",
      "damaged":"false",
      "automated":"true",
      "fuel":"true",
      "country_from":"Polska",
      "post_id":"123abc456d7",
      "url":"https://examplepicturelink.com/xyz.jpg",
      "region":"Kujawsko-pomorskie",
      "city":"Bydgoszcz",
      "description":"Samochód z salonu, bardzo polecam!",
      "created_at":"29-04-2019"
}} // and more records

将数据下载到应用程序运行良好

DataCar 和汽车模型:

public class DataCar {
public ArrayList<Car> getCars() {
    return cars;
}

public void setCars(ArrayList<Car> cars) {
    this.cars = cars;
}

private ArrayList<Car> cars;
}



import com.google.gson.annotations.SerializedName;

public class Car {

@SerializedName("image_url")
private String image_url;
@SerializedName("brand")
private String brand;
@SerializedName("model")
private String model;
@SerializedName("price")
private Double price;
@SerializedName("engine")
private String engine;
@SerializedName("year")
private Integer year;
@SerializedName("hp")
private Integer hp;
@SerializedName("mileage")
private Integer mileage;
@SerializedName("color")
private String color;
@SerializedName("damaged")
private Boolean damaged;
@SerializedName("automated")
private Boolean automated;
@SerializedName("fuel")
private Boolean fuel;
@SerializedName("country_from")
private String country_from;
@SerializedName("post_id")
private String post_id;
@SerializedName("url")
private String url;
@SerializedName("region")
private String region;
@SerializedName("city")
private String city;
@SerializedName("description")
private String description;
@SerializedName("created_at")
private String created_at;
//getters + setters + constructors
}

【问题讨论】:

    标签: java android json elasticsearch httprequest


    【解决方案1】:

    考虑到它的功能,我宁愿使用FasterXML/Jackson 而不是“Google Gson”。如果您使用 Maven 进行依赖项管理,则需要以下依赖项,否则将每个依赖项添加到您的 classpath

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

    对于您的问题,您可以尝试对您的 POJO 进行类似的操作。

    @JsonInclude(JsonInclude.Include.NON_NULL)  // This will exclude null JSON attributes.
    @JsonIgnoreProperties(ignoreUnknown = true) // This will exclude any unknown(not available in the class) attribute in the JSON string.
    public class Car {
    
        @JsonProperty("image_url") // No matter if you didn't use this annotation. Jackson will automatically bind the variable name.
        private String image_url;
    
        @JsonProperty("brand")
        private String brand;
    
        @JsonProperty("model")
        private String model;
    
        @JsonProperty("price")
        private Double price;
    
        @JsonProperty("engine")
        private String engine;
    
        @JsonProperty("year")
        private Integer year;
    
        @JsonProperty("hp")
        private Integer hp;
    
        @JsonProperty("mileage")
        private Integer mileage;
    
        @JsonProperty("color")
        private String color;
    
        // Omitted the rest.
    }
    

    现在要反序列化 JSON 字符串,您需要一个这样的函数。

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.type.CollectionType;
    import java.io.IOException;
    import java.util.List;
    
    public class JsonProcessor { // This implementation can change as you want.
    
        public static <T> List<T> unmarshallToList(String json, Class<T> classType)
                throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            CollectionType javaType = mapper.getTypeFactory() // Check here whether you can take different function to directly de-serialize to the object than to a List.
                    .constructCollectionType(List.class, classType);
    
            return mapper.readValue(json, javaType);
        }
    }
    

    当您调用unmarshallToList 函数时,您需要传递JSON String 和类类型,该函数将返回您的对象的List

    List<Car> cars = JsonProcessor.unmarshallToList(jsonString, Car.class);
    

    如果您的 JSON 对象还不能工作,请尝试使用 [ ] 包装 JSON 字符串以将其暗示为 JSON Array

    如果您对unmarshallToList 函数进行任何更改,您 需要相应地调整您的 JSON 字符串。检查this documentation 了解您可以做些什么来更改退货 函数的类型。

    【讨论】:

      猜你喜欢
      • 2012-08-29
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多