Конвертировать JSON из Elasticsearch в объект Java - PullRequest
0 голосов
/ 14 июня 2019

У меня проблема с функцией gson.fromJson. Я получаю JSON от моего ElasticSearch. Я могу преобразовать тело в строку, но не могу преобразовать это в объект. Может быть, я должен использовать что-то еще, чем 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
}

1 Ответ

1 голос
/ 14 июня 2019

Я бы предпочел использовать 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 соответственно. Проверьте это документация , чтобы понять, что вы можете сделать, чтобы изменить возврат тип функции.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...