GSON:预期的BEGIN_OBJECT,但却是STRING

2022-09-03 14:08:20

我收到一个GSON错误,试图将JSON解构到一个对象中。错误(预期BEGIN_OBJECT,但在第 3 行第 22 列处为 STRING)指向下面输入的第 3 行。

我是否没有针对 Bean 正确映射 JSON?

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"
    }
}

答案 1

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

您可以创建一个类来封装您的类,但是将容器反序列化为使用会更干净BusinessPartnerCreatejsonObject

 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;

(邮政编码类似)


答案 2