bibliophilsagar
bibliophilsagar

Reputation: 1753

want to map a json object unto a java object

I am using a certain API which have a json output as below. I have parsed it to String. the json output as string: {"result":{"number":"INC0022500"}}.

As you can see it has nested object for key result.

my snippet which i am using to map the above json unto a object.

Gson gson = new Gson();
EspIncidentTrial staff = gson.fromJson(json, EspIncidentTrial.class);

ESPIncidentTrial class:

import javax.persistence.Embeddable;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

@Embeddable
@JsonIgnoreProperties(ignoreUnknown = true)
public class EspIncidentTrial {
    @JsonProperty("result")
    private ResultTrial result;

    public ResultTrial getResult() {
        return result;
    }

    public void setResult(ResultTrial result) {
        this.result = result;
    }

}

For the nested object i created another class ResultTrial. Below is the body.

ResultTrial class:

import javax.persistence.Embeddable;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

@Embeddable
@JsonIgnoreProperties(ignoreUnknown = true)
public class ResultTrial {
    @JsonProperty("number")
    private String incidentId;

    public String getIncidentId() {
        return incidentId;
    }

    public void setIncidentId(String incidentId) {
        this.incidentId = incidentId;
    }
}

What happens now is, in EspIncidentTrial class, object result is getting mapped. However, inside ResultTrial class, no mapping is being done.

I tried treating the key result in the json object as String, but the threw the below error, which was expected though.

The error occured while parsing the JSON. com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 12 path $.result

Please help!

Upvotes: 0

Views: 65

Answers (2)

Rinku Jagdale
Rinku Jagdale

Reputation: 11

you can try this....

String searchdata="{\"userPojo\":{\"userid\":1156}}";

JSONObject jsonObject=new JSONObject(searchdata);

SummaryPojo summaryPojo=new SummaryPojo();

if(searchdata.contains("userPojo"))

{

String jsonstring=jsonObject.getString("userPojo");

Gson gson = new Gson();

UserPojo userPojo = gson.fromJson(searchdata, UserPojo.class);

summaryPojo.setUserPojo(userPojo);

}

Upvotes: 0

Sachin Gupta
Sachin Gupta

Reputation: 8358

Here you are mixing gson and Jackson. You are using annoations of Jackson, but using GSON's method to deserailze it.

Use Jackson's objectMapper to deserialize.

E.g.:

ObjectMapper mapper = new ObjectMapper();
EspIncidentTrial staff = mapper.readValue(json, EspIncidentTrial.class);

Upvotes: 1

Related Questions