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\",
...
}
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.
Main:
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);
Customer
public class Customer {
@SerializedName("cust_id")
private List custId;
public List getCustId() {
return custId;
}
public void setCustId(List custId) {
this.custId = custId;
}
}
CustomerDeserializer
public class CustomerDeserializer implements JsonDeserializer {
@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;
}
}
Output
Customer [custId=[87655]]
Customer [custId=[12345, 45678]]