为什么GSON在解析一组对象数组时会给我一个错误?

时间:2017-10-14 01:44:15

标签: java arrays json object gson

JSON:

[{"DataContainer": {
      "ShoppingDetails": [
        [
          {
            "Value": "3",
            "Name": "Price"
          },
          {
            "Value": "XAV-13-9LO",
            "Name": "Item Code"
          }
        ],
        [
          {
            "Value": "9",
            "Name": "Price"
          },
          {
            "Value": "WEB-13-9XH",
            "Name": "Item Code"
          }
        ]
      ]
    }
 }]

我已经有一个DataContainer类:

public class DataContainer extends WebResp{
    @SerializedName("ShoppingDetails")
    private ShoppingDetails[] shoppingDetails;

    public ShoppingDetails[] getShoppingDetails() {
        return shoppingDetails;
    }

    public void setShoppingDetails(ShoppingDetails[] shoppingDetails) {
        this.shoppingDetails= shoppingDetails;
    }
}

和类ShoppingDetails:

public class ShoppingDetails{
    private Field[] field;

    public Field[] getField() {
        return field;
    }

    public void setField(Field[] field) {
        this.field= field;
   }
}

但不幸的是,我结束了 com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期BEGIN_OBJECT但是第61行第10行BEGIN_ARRAY路径$ [0] .DataContainer.ShoppingDetails [0]

有人能指出我正确的方向,使用GSON将此JSON映射到Java对象吗?

1 个答案:

答案 0 :(得分:0)

  • 添加DataBean

  • 使用Gson解析它

<强> 1.DataBean

public class DataBean {

private DataContainerBean DataContainer;

public DataContainerBean getDataContainer() {
    return DataContainer;
}

public void setDataContainer(DataContainerBean DataContainer) {
    this.DataContainer = DataContainer;
}

public static class DataContainerBean {
    /**
     * Value : 3
     * Name : Price
     */

    private List<List<ShoppingDetailsBean>> ShoppingDetails;

    public List<List<ShoppingDetailsBean>> getShoppingDetails() {
        return ShoppingDetails;
    }

    public void setShoppingDetails(List<List<ShoppingDetailsBean>> ShoppingDetails) {
        this.ShoppingDetails = ShoppingDetails;
    }

    public static class ShoppingDetailsBean {
        private String Value;
        private String Name;

        public String getValue() {
            return Value;
        }

        public void setValue(String Value) {
            this.Value = Value;
        }

        public String getName() {
            return Name;
        }

        public void setName(String Name) {
            this.Name = Name;
        }
    }
}
}

2.使用Gson tp解析

Gson gson = new Gson();
try {
    JSONArray jsonArray = new JSONArray(response);
    for (int i = 0; i < jsonArray.length(); i++) {
        DataBean dataBean = gson.fromJson(jsonArray.getJSONObject(i).toString(),DataBean.class);
    }
} catch (JSONException e) {
    e.printStackTrace();
}