我对gson.fromJson
函数有疑问。我从ElasticSearch获取JSON。我可以将主体转换为String,但不能将其转换为Object。也许我还应该再用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和Car模型:
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
}
答案 0 :(得分: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,以了解如何更改退货 函数的类型。