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",
...
},
or a few ids as an array:
{
"cust_id": [
"12345",
"45678"
],
...
},
The Customer
class is as below:
public class Customer {
@SerializedName("cust_id")
@Expose
private String custId;
public String getCustId() {
return custId;
}
public void setCustId(String custId) {
this.custId = custId;
}
}
I parse the JSON using Gson:
Gson gson = new Gson()
Customers customers1 = gson.fromJson(json, Customers.class)
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.
The reason of failure is clear.
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?