gpt4 book ai didi

java - 将 JSON 从 Elasticsearch 转换为 Java 对象

转载 作者:行者123 更新时间:2023-12-02 09:46:45 26 4
gpt4 key购买 nike

我的 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
}

最佳答案

我宁愿使用FasterXML/Jackson考虑到其功能,它比“Google Gson”要好。如果您使用 Maven 进行依赖项管理,则需要以下依赖项,否则将每个依赖项添加到您的类路径中。

<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 数组

If you do any change to unmarshallToList function, you need adjust your JSON string accordingly. Check this documentation to understand what you can do to change the return type of the function.

关于java - 将 JSON 从 Elasticsearch 转换为 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56589743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com