Gson: How do I parse polymorphic values that can be either lists or strings?

前端 未结 4 459
心在旅途
心在旅途 2021-01-27 11:57

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\",
  ...
}         


        
4条回答
  •  庸人自扰
    2021-01-27 12:22

    You can just simply specify all values as array, even if is just one value.

    {
      "cust_id": ["87655"],
      ...
    },
    

    UPDATE: If you cannot change the json, you can bind every field in Customer class except custId and set it manually.

    public class Customer {
        private String[] custId;
    
        public String getCustId() {
            return custId;
        }
    
        public void setCustId(String custId) {
            custId = new String[] {custId};
        }
    
        public void setCustId(String[] custId) {
            this.custId = custId;
        }
    }
    

    And then parse manually:

    Gson gson = new Gson();
    Customers customers = gson.fromJson(json, Customers.class);
    Object custId = new JSONObject(json).get("cust_id");
    if (custId instanceof String) {
      customers.setCustId((String) custId);
    else if (custId instanceof JSONArray) {
      customers.setCustId(convertToStringArray(new JSONArray(custId)));
    }
    

提交回复
热议问题