Gson:如何解析可以是列表或字符串的多态值? [英] Gson: How do I parse polymorphic values that can be either lists or strings?
问题描述
我需要解析一个包含一长串客户的JSON文件.在JSON文件中,每个客户都可以使用一个ID作为字符串:
I need to parse a JSON file that contains long list of customers. In the JSON file each customer may have one id as a string:
{
"cust_id": "87655",
...
},
或一些ID作为数组:
{
"cust_id": [
"12345",
"45678"
],
...
},
Customer
类如下:
public class Customer {
@SerializedName("cust_id")
@Expose
private String custId;
public String getCustId() {
return custId;
}
public void setCustId(String custId) {
this.custId = custId;
}
}
我使用Gson解析JSON:
I parse the JSON using Gson:
Gson gson = new Gson()
Customers customers1 = gson.fromJson(json, Customers.class)
,并且在尝试解析数组时失败,并显示com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY
.
and it fails with com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY
when it attempts to parse the array.
失败的原因很清楚.
我的问题:在给定我无法更改json文件结构的情况下,处理这两种情况(ID为字符串且为字符串数组)的最佳方法是什么?>
My question: what is the best way to handle both cases (when id is a string and when it is an array of strings), given I can not change the json file structure?
推荐答案
如果要同时处理这两种情况,则可以使用自定义解串器.当然,您必须将"cust_id"变量更改为列表或数组.
If you want to handle both scenarios you can use a custom deserializer. Of course, you have to change the "cust_id" variable to be a list or an array.
主要:
String json1 = "{\"cust_id\": \"87655\"}";
String json2 = "{\"cust_id\": [\"12345\", \"45678\"]}";
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Customer.class, new CustomerDeserializer());
Gson gson = gsonBuilder.create();
Customer customer1 = gson.fromJson(json1, Customer.class);
System.out.println(customer1);
Customer customer2 = gson.fromJson(json2, Customer.class);
System.out.println(customer2);
客户
public class Customer {
@SerializedName("cust_id")
private List<String> custId;
public List<String> getCustId() {
return custId;
}
public void setCustId(List<String> custId) {
this.custId = custId;
}
}
CustomerDeserializer
CustomerDeserializer
public class CustomerDeserializer implements JsonDeserializer<Customer> {
@Override
public Customer deserialize(JsonElement jsonElement, Type typeOf, JsonDeserializationContext context) throws JsonParseException {
Customer result = null;
Gson gson = new Gson();
try {
// try to deserialize by assuming JSON has a list
result = gson.fromJson(jsonElement, Customer.class);
} catch (JsonSyntaxException jse) {
// error here means JSON has a single string instead of a list
try {
// get the single ID
String custId = jsonElement.getAsJsonObject().get("cust_id").getAsString();
result = new Customer();
result.setCustId(Arrays.asList(new String[] {custId}));
} catch (Exception e) {
// more error handling here
e.printStackTrace();
}
}
return result;
}
}
输出
Customer [custId=[87655]]
Customer [custId=[12345, 45678]]
这篇关于Gson:如何解析可以是列表或字符串的多态值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!