15

我在尝试将 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"
    }
}
4

1 回答 1

19

不,您没有正确映射它,因为您的 json 对象不是 a BusinessPartnerCreate,它包含 a 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;

(和类似的邮政编码)

于 2012-06-26T19:37:53.790 回答