【问题标题】:GSON: Expected BEGIN_OBJECT but was STRINGGSON:应为 BEGIN_OBJECT,但为 STRING
【发布时间】:2017-01-10 16:40:22
【问题描述】:

我在尝试将 JSON 解组为对象时遇到 GSON 错误。错误(Expected BEGIN_OBJECT but was STRING at line 3 column 22)指向下面输入的第 3 行。

我是否没有正确地将 JSON 映射到 Bean?

import javax.xml.bind.JAXBElement;

public class BusinessPartnerCreate {
    protected JAXBElement<String> partnerType;
    protected Person person;
    protected Company company;
    protected String email;
    protected String phone;
    protected AddressData addressData;
    protected AddressClean addressClean;
    protected String city;
    protected String state;
    protected String zipCode;
    protected JAXBElement<String> externalId;
}

我的输入 JSON 看起来是这样的:

{
    "business-partner-create": {
        "partner-type": "1",
        "person": {
            "firstName": "Dirk",
            "lastName": "Wintermill",
            "title": ""
        },
        "email": "kirk@yahoo.com",
        "phone": "219-385-2946",
        "addressClean": {
            "house-number": "10218",
            "street-name": "Park",
            "street-abbr": "Rd"
        },
        "city": "Somerset",
        "state": "NJ",
        "zip-code": "01955"
    }
}

【问题讨论】:

    标签: java json


    【解决方案1】:

    不,您没有正确映射它,因为您的 json 对象不是BusinessPartnerCreate,它包含BusinessPartnerCreate

    您可以创建一个类来封装您的BusinessPartnerCreate,但使用将容器反序列化为jsonObject 会更简洁

     JsonParser parser = new JsonParser();
     JsonObject obj = parser.parse(json).getAsJsonObject();
    

    然后使用解析有趣的内容

    BusinessPartnerCreate bpc = gson.fromJson(obj.get("business-partner-create"), BusinessPartnerCreate.class);
    

    我建议您添加一个注释以确保正确映射partnerType 字段:

       @SerializedName "partner-type"
       protected JAXBElement<String> partnerType;
    

    (和类似的邮政编码)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-15
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多