2012-06-26 9 views
15

Viene visualizzato un errore di GSON durante il tentativo di JSON unmarshal in un oggetto. L'errore (previsto BEGIN_OBJECT ma era STRING alla riga 3 colonna 22) punta alla riga 3 dell'ingresso di seguito.GSON: Previsto BEGIN_OBJECT, ma era STRING

Non ho mappato correttamente il JSON rispetto al 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; 
} 

E il mio ingresso JSON aspetto è questo:

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

risposta

18

No, non hai mappato in modo corretto come oggetto JSON non è una BusinessPartnerCreate, contiene una BusinessPartnerCreate.

È possibile creare una classe solo per incapsulare il tuo BusinessPartnerCreate ma sarebbe più pulito per deserializzare il contenitore come jsonObject utilizzando

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

e quindi analizzare il contenuto interessante utilizzando

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

E io suggerire di aggiungere un'annotazione per garantire una corretta mappatura del campo partnerType:

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

(e simile per codice postale)

Problemi correlati