我在尝试将JSON解组为对象时遇到GSON错误。错误(预期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"
}
}
答案 0 :(得分:19)
不,您没有正确映射,因为您的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;
(和邮政编码类似)