我在尝试将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" } }
不,您没有正确映射它,因为您的json对象不是BusinessPartnerCreate,它包含BusinessPartnerCreate。
BusinessPartnerCreate
你可以创建一个类只是为了封装你BusinessPartnerCreate,但它是清洁反序列化容器的jsonObject使用
jsonObject
JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(json).getAsJsonObject();
然后使用解析有趣的内容
BusinessPartnerCreate bpc = gson.fromJson(obj.get("business-partner-create"), BusinessPartnerCreate.class);
并且我建议您添加注释以确保partnerType字段的正确映射:
partnerType
@SerializedName "partner-type" protected JAXBElement<String> partnerType;
(和类似的邮政编码)