Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

java - GSON: Expected BEGIN_OBJECT but was STRING

I am getting a GSON error trying to unmarshal JSON into an object. The error (Expected BEGIN_OBJECT but was STRING at line 3 column 22) is pointing to line 3 of the input below.

Have I not mapped the JSON correctly with respect to the 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;
}

And my input JSON looks is this:

{
    "business-partner-create": {
        "partner-type": "1",
        "person": {
            "firstName": "Dirk",
            "lastName": "Wintermill",
            "title": ""
        },
        "email": "[email protected]",
        "phone": "219-385-2946",
        "addressClean": {
            "house-number": "10218",
            "street-name": "Park",
            "street-abbr": "Rd"
        },
        "city": "Somerset",
        "state": "NJ",
        "zip-code": "01955"
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, you've not mapped it correctly as your json object isn't a BusinessPartnerCreate, it contains a BusinessPartnerCreate.

You can create a class just to encapsulate your BusinessPartnerCreate but it would be cleaner to deserialize the container as a jsonObject using

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

and then parse the interesting content using

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

And I suggest you add an annotation to ensure proper mapping of the partnerType field :

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

(and similar for zip-code)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...