How to parse JSON Text in Java [duplicate] - java

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
I have the following JSON text. How can I parse it to get response-code, response, result, DISPLAYNAME ,AVAILABILITYSEVERITY, RESOURCEID , ETC?
{
"response-code":"4000",
"response":
{
"result":
[
{
"DISPLAYNAME":"Backup Server",
"AVAILABILITYSEVERITY":"5",
"RESOURCEID":"10002239110",
"TYPE":"SUN",
"SHORTMESSAGE":"Clear"
}
]
,"uri":"/json/ListAlarms"
}
}

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public static void main(String[] args) {
final String json = "{ \"response-code\":\"4000\", \"response\": { \"result\": [ { \"DISPLAYNAME\":\"Backup Server\", \"AVAILABILITYSEVERITY\":\"5\", \"RESOURCEID\":\"10002239110\", \"TYPE\":\"SUN\", \"SHORTMESSAGE\":\"Clear\" } ] ,\"uri\":\"/json/ListAlarms\" } }";
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode obj = mapper.readTree(json);
System.out.println(obj.get("response-code"));
JsonNode response = obj.get("response");
JsonNode firstResult = response.get("result").get(0);
System.out.println(firstResult.get("DISPLAYNAME"));
System.out.println(firstResult.get("AVAILABILITYSEVERITY"));
System.out.println(firstResult.get("RESOURCEID"));
System.out.println(firstResult.get("TYPE"));
System.out.println(firstResult.get("SHORTMESSAGE"));
System.out.println(response.get("uri"));
} catch (IOException e) {
e.printStackTrace();
}
}
output
"4000"
"Backup Server"
"5"
"10002239110"
"SUN"
"Clear"
"/json/ListAlarms"
another approach only if the json has fixed structure, is to build objects to represent the json structure and use jackson to cast that json to a java object, like
class JsonObj {
#JsonProperty("response-code")
private long responseCode;
private ResponseObj response;
public long getResponseCode() {
return responseCode;
}
public void setResponseCode(long responseCode) {
this.responseCode = responseCode;
}
public ResponseObj getResponse() {
return response;
}
public void setResponse(ResponseObj response) {
this.response = response;
}
}
class ResponseObj {
private ArrayList<ResultObj> result;
private String uri;
public ArrayList<ResultObj> getResult() {
return result;
}
public void setResult(ArrayList<ResultObj> result) {
this.result = result;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
}
class ResultObj {
#JsonProperty("DISPLAYNAME")
private String displayName;
#JsonProperty("TYPE")
private String type;
#JsonProperty("AVAILABILITYSEVERITY")
private int availabilitySeverity;
#JsonProperty("RESOURCEID")
private String resourceId;
#JsonProperty("SHORTMESSAGE")
private String shortMessage;
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAvailabilitySeverity() {
return availabilitySeverity;
}
public void setAvailabilitySeverity(int availabilitySeverity) {
this.availabilitySeverity = availabilitySeverity;
}
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
public String getShortMessage() {
return shortMessage;
}
public void setShortMessage(String shortMessage) {
this.shortMessage = shortMessage;
}
}
and then, access the values like that
JsonObj jsonObj = mapper.readValue(json, JsonObj.class);
System.out.println(jsonObj.getResponseCode());
ResponseObj response = jsonObj.getResponse();
ResultObj firstResult = response.getResult().get(0);
System.out.println(firstResult.getDisplayName());
System.out.println(firstResult.getAvailabilitySeverity());
System.out.println(firstResult.getResourceId());
System.out.println(firstResult.getType());
System.out.println(firstResult.getShortMessage());
System.out.println(response.getUri());
the output is the same...

Related

Convert json string response to pojo

I am calling an API using rest template like below:
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
And here is the json response string that i receive from the API
{
"data": {
"individuals": [
{
"cust_xref_id": "abf",
"cust_frd_alrt_in": "n",
"cust_satis_trd_ct": "4",
"gam_open_rv_trd_ct": "4",
"cust_extnl_delinq_90_day_ct": "1",
"cust_extnl_delinq_in": "y"
}
]
}
}
how can i map this response into a pojo? please help.
Required classes for the conversion are below,
1. DataDTO
public class DataDTO {
private IndividualList data;
public IndividualList getData() {
return data;
}
public void setData(IndividualList data) {
this.data = data;
}}
2. IndividualList
public class IndividualList {
private List<IndividualDTO> individuals;
public List<IndividualDTO> getIndividuals() {
return individuals;
}
public void setIndividuals(List<IndividualDTO> individuals) {
this.individuals = individuals;
}}
3. IndividualDTO
public class IndividualDTO {
#JsonProperty("cust_xref_id")
private String custXrefId;
#JsonProperty("cust_frd_alrt_in")
private String custFrdAlrtIn;
#JsonProperty("cust_satis_trd_ct")
private String custSatisTrdCt;
#JsonProperty("gam_open_rv_trd_ct")
private String gamOpenRvTrdCt;
#JsonProperty("cust_extnl_delinq_90_day_ct")
private String custExtnlDelinq90DayCt;
#JsonProperty("cust_extnl_delinq_in")
private String custExtnlDelinqIn;
public String getCustXrefId() {
return custXrefId;
}
public void setCustXrefId(String custXrefId) {
this.custXrefId = custXrefId;
}
public String getCustFrdAlrtIn() {
return custFrdAlrtIn;
}
public void setCustFrdAlrtIn(String custFrdAlrtIn) {
this.custFrdAlrtIn = custFrdAlrtIn;
}
public String getCustSatisTrdCt() {
return custSatisTrdCt;
}
public void setCustSatisTrdCt(String custSatisTrdCt) {
this.custSatisTrdCt = custSatisTrdCt;
}
public String getGamOpenRvTrdCt() {
return gamOpenRvTrdCt;
}
public void setGamOpenRvTrdCt(String gamOpenRvTrdCt) {
this.gamOpenRvTrdCt = gamOpenRvTrdCt;
}
public String getCustExtnlDelinq90DayCt() {
return custExtnlDelinq90DayCt;
}
public void setCustExtnlDelinq90DayCt(String custExtnlDelinq90DayCt) {
this.custExtnlDelinq90DayCt = custExtnlDelinq90DayCt;
}
public String getCustExtnlDelinqIn() {
return custExtnlDelinqIn;
}
public void setCustExtnlDelinqIn(String custExtnlDelinqIn) {
this.custExtnlDelinqIn = custExtnlDelinqIn;
}}
Tested Response:
{"data":{"individuals":[{"cust_xref_id":"abf","cust_frd_alrt_in":"n","cust_satis_trd_ct":"4","gam_open_rv_trd_ct":"4","cust_extnl_delinq_90_day_ct":"1","cust_extnl_delinq_in":"y"}]}}

Android: parse JSON response when a key can be a JSON object or a JSON array

I am fetching data from API provided by our Backend team. One of the keys data sometimes contains JSONObject and sometimes it contains JSONArray. I am using GSON to parse the response and it is throwing an exception because of this.
I tried the solution given in this thread but it's not working in my case.
How to dynamically handle json response array/object using Gson
POJO (EntityDetailResponseV2):
package com.tf.eros.faythTv.objects.entityDetail;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import com.tf.eros.faythTv.objects.entityFeatured.EntityFeaturedResponse;
import com.tf.eros.faythTv.utils.ArrayAdapterFactory;
import java.util.List;
public class EntityDetailResponseV2 {
#SerializedName("results")
private Results results;
#SerializedName("success")
private boolean success;
public static EntityDetailResponseV2 getObject(String res) {
try {
Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create();
return gson.fromJson(res, EntityDetailResponseV2.class);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Results getResults() {
return results;
}
public boolean isSuccess() {
return success;
}
public static class Results {
#SerializedName("id")
Integer entityID;
#SerializedName("name")
String entityName;
#SerializedName("description")
String entityDescription;
#SerializedName("image_url")
String entityImageURL;
#SerializedName("square_entity_url")
String entitySquareURL;
#SerializedName("slug")
String entitySlug;
#SerializedName("live")
boolean isEntityLive;
#SerializedName("twitter_username")
String twitterUserName;
#SerializedName("fb_username")
String fbUserName;
#SerializedName("featured")
private List<EntityFeaturedResponse> featured;
#SerializedName("collections")
List<Collections> collectionsList;
public Integer getEntityID() {
return entityID;
}
public String getEntityName() {
return entityName;
}
public String getEntityDescription() {
return entityDescription;
}
public String getEntityImageURL() {
return entityImageURL;
}
public String getEntitySquareURL() {
return entitySquareURL;
}
public String getEntitySlug() {
return entitySlug;
}
public boolean isEntityLive() {
return isEntityLive;
}
public String getTwitterUserName() {
return twitterUserName;
}
public String getFbUserName() {
return fbUserName;
}
public List<EntityFeaturedResponse> getFeatured() {
return featured;
}
public List<Collections> getCollectionsList() {
return collectionsList;
}
public static class Collections {
#SerializedName("type")
String type;
#SerializedName("type_id")
Integer typeID;
//Data sometimes contains JSON object and sometimes it contains JSON Array
#SerializedName("data")
List<Data> data;
public String getType() {
return type;
}
public Integer getTypeID() {
return typeID;
}
public List<Data> getData() {
return data;
}
public static class Data {
#SerializedName("view_all")
boolean viewAll;
#SerializedName("title")
String title;
public boolean isViewAll() {
return viewAll;
}
public String getTitle() {
return title;
}
}
}
}
}
ArrayAdapterFactory.java
public class ArrayAdapterFactory implements TypeAdapterFactory {
#SuppressWarnings({"unchecked"})
#Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
ArrayAdapter typeAdapter = null;
try {
if (type.getRawType() == List.class) {
typeAdapter = new ArrayAdapter(
(Class) ((ParameterizedType) type.getType())
.getActualTypeArguments()[0]);
}
} catch (Exception e) {
e.printStackTrace();
}
return typeAdapter;
}
public class ArrayAdapter<T> extends TypeAdapter<List<T>> {
private Class<T> adapterClass;
public ArrayAdapter(Class<T> adapterClass) {
this.adapterClass = adapterClass;
}
public List<T> read(JsonReader reader) throws IOException {
List<T> list = new ArrayList<T>();
Gson gson = new Gson();
if (reader.peek() == JsonToken.BEGIN_OBJECT) {
T inning = (T) gson.fromJson(reader, adapterClass);
list.add(inning);
} else if (reader.peek() == JsonToken.BEGIN_ARRAY) {
reader.beginArray();
while (reader.hasNext()) {
//read(reader);
T inning = (T) gson.fromJson(reader, adapterClass);
list.add(inning);
}
reader.endArray();
} else {
reader.skipValue();
}
return list;
}
public void write(JsonWriter writer, List<T> value) throws IOException {
}
}
}
As complete API response is very large, I am providing a link to .json file. https://drive.google.com/open?id=1RMOiM7UjOwR-5b0Ik7ymy65ZOhc8I8hY
UPDATE:
I tried the solution which is mentioned below but still, DataType1 and DataType2 both are coming nulls. Although I am no longer getting the GSON exception.
public class EntityDetailResponseV2 {
#SerializedName("results")
private Results results;
#SerializedName("success")
private boolean success;
public static EntityDetailResponseV2 getObject(String res) {
try {
Gson gson = new GsonBuilder().registerTypeAdapter(Collections.class, new Results.Collections.CollectionItemDeserializer()).create();
return gson.fromJson(res, EntityDetailResponseV2.class);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Results getResults() {
return results;
}
public boolean isSuccess() {
return success;
}
public static class Results {
#SerializedName("id")
Integer entityID;
#SerializedName("name")
String entityName;
#SerializedName("description")
String entityDescription;
#SerializedName("image_url")
String entityImageURL;
#SerializedName("square_entity_url")
String entitySquareURL;
#SerializedName("slug")
String entitySlug;
#SerializedName("live")
boolean isEntityLive;
#SerializedName("twitter_username")
String twitterUserName;
#SerializedName("fb_username")
String fbUserName;
#SerializedName("featured")
private List<EntityFeaturedResponse> featured;
#SerializedName("collections")
List<Collections> collectionsList;
public Integer getEntityID() {
return entityID;
}
public String getEntityName() {
return entityName;
}
public String getEntityDescription() {
return entityDescription;
}
public String getEntityImageURL() {
return entityImageURL;
}
public String getEntitySquareURL() {
return entitySquareURL;
}
public String getEntitySlug() {
return entitySlug;
}
public boolean isEntityLive() {
return isEntityLive;
}
public String getTwitterUserName() {
return twitterUserName;
}
public String getFbUserName() {
return fbUserName;
}
public List<EntityFeaturedResponse> getFeatured() {
return featured;
}
public List<Collections> getCollectionsList() {
return collectionsList;
}
public static class Collections {
#SerializedName("type")
String type;
#SerializedName("order")
Integer order;
#SerializedName("type_id")
Integer typeId;
DataType1 dataType1;
List<DataType2> dataType2;
public String getType() {
return type;
}
public Integer getOrder() {
return order;
}
public Integer getTypeId() {
return typeId;
}
public DataType1 getDataType1() {
return dataType1;
}
public List<DataType2> getDataType2() {
return dataType2;
}
public static class CollectionItemDeserializer implements JsonDeserializer<Collections> {
#Override
public Collections deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Collections collectionItem = new Gson().fromJson(json, Collections.class);
JsonObject jsonObject = json.getAsJsonObject();
if (collectionItem.getType() != null) {
JsonElement element = jsonObject.get("data");
switch (collectionItem.getTypeId()) {
case AppConstants.ENTITY_SHOP:
case AppConstants.ENTITY_MEDIA_COLLECTION:
case AppConstants.ENTITY_ECOM_COLLECTION:
case AppConstants.ENTITY_BANNER:
collectionItem.dataType1 = new Gson().fromJson(element, DataType1.class);
break;
case AppConstants.ENTITY_TOP_AUDIOS:
case AppConstants.ENTITY_TOP_VIDEOS:
case AppConstants.ENTITY_LATEST_VIDEOS:
case AppConstants.ENTITY_TOP_PLAYLISTS:
case AppConstants.ENTITY_WALLPAPERS:
case AppConstants.ENTITY_QUOTATIONS:
List<DataType2> values = new Gson().fromJson(element, new TypeToken<ArrayList<DataType2>>() {}.getType());
collectionItem.dataType2 = values;
break;
}
}
return collectionItem;
}
}
public static class DataType1 {
#SerializedName("view_all")
boolean viewAll;
public boolean isViewAll() {
return viewAll;
}
}
public static class DataType2 {
#SerializedName("view_all")
boolean viewAll;
public boolean isViewAll() {
return viewAll;
}
}
}
}
}
You need to use a custom JsonDeserializer. Here's the solution :
public class CollectionListItem {
#SerializedName ("type")
String type;
#SerializedName ("order")
Integer order;
#SerializedName ("id")
Integer id;
#SerializedName ("type_id")
Integer typeId;
DataType1 dataType1;
List<DataType2> dataType2;
List<DataType3> dataType3;
final static String DATA_TYPE_1 = "SHOP";
final static String DATA_TYPE_2 = "TOP_AUDIOS";
final static String DATA_TYPE_3 = "MEDIA_COLLECTION";
//Public getters and setters
public static class CollectionItemDeserializer implements JsonDeserializer<CollectionListItem> {
#Override
public CollectionListItem deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
CollectionListItem collectionItem = new Gson().fromJson(json, CollectionListItem.class);
JsonObject jsonObject = json.getAsJsonObject();
if (collectionItem.getType() != null) {
JsonElement element = jsonObject.get("data");
switch(collectionItem.getType()){
case CollectionListItem.DATA_TYPE_1 :
collectionItem.dataType1 = new Gson().fromJson(element, DataType1.class);
break;
case CollectionListItem.DATA_TYPE_2:
List<DataType2> values = new Gson().fromJson(element, new TypeToken<ArrayList<DataType2>>() {}.getType());
collectionItem.dataType2 = values;
break;
case CollectionListItem.DATA_TYPE_3:
List<DataType3> values_ = new Gson().fromJson(element, new TypeToken<ArrayList<DataType3>>() {}.getType());
collectionItem.dataType3 = values_;
break;
}
}
return collectionItem;
}
}
}
DataType1, DataType2, etc are the individual classes for different responses.
Also, add this line to register your custom deserializer with gson
Gson gson = new GsonBuilder()
.registerTypeAdapter(CollectionListItem.class,
new CollectionListItem.CollectionItemDeserializer())
.create();

JSON mapping to Java returning null value

I'm trying to map JSON to Java using gson.I was succesful in writing the logic but unsuccesful in getting the output.Below posted are my JSON and Java files.Any help would be highly appreciated.
This is the output i'm getting
value:null
Below posted is the code for .json files
{
"catitem": {
"id": "1.196289",
"src": "http://feeds.reuters.com/~r/reuters/MostRead/~3/PV-SzW7Pve0/story06.htm",
"orig_item_date": "Tuesday 16 June 2015 07:01:02 PM UTC",
"cat_id": "1",
"heding": "Putin says Russia beefing up nuclear arsenal",
"summary": "KUvdfbefb bngfb",
"body": {
"bpart": [
"KUBINKA,dvdvdvdvgbtgfdnhfbnrtdfbcv dbnfg"
]
}
}
}
Below posted is my .java file
public class offc {
public static void main(String[] args) {
JsonReader jr = null;
try {
jr = new JsonReader(new InputStreamReader(new FileInputStream(
"C:\\Users\\rishii\\IdeaProjects\\rishi\\src\\file3.json")));
} catch (Exception ex) {
ex.printStackTrace();
}
Doll s = new Doll();
Gson g = new Gson();
Doll sr1 = g.fromJson(jr, Doll.class);
System.out.println(sr1);
}
}
Below posted is the code for Doll.java
class Doll {
private catitem ct;
public void setCt(catitem ct) {
this.ct = ct;
}
public catitem getCt() {
return ct;
}
#Override
public String toString()
{
return "value:" + ct;
}
class catitem {
private String id;
private String src;
private String orig_item_date;
private String cat_id;
private String heding;
private String summary;
private body ber;
catitem(String id, String src, String orig_item_date, String cat_id, String heding,
String summary) {
this.id = id;
this.src = src;
this.orig_item_date = orig_item_date;
this.cat_id = cat_id;
this.heding = heding;
this.summary = summary;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setSrc(String src) {
this.src = src;
}
public String getSrc() {
return src;
}
public void setOrig_item_date(String Orig_item_date) {
this.orig_item_date = Orig_item_date;
}
public String getOrig_item_date() {
return getOrig_item_date();
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getCat_id() {
return cat_id;
}
public void setHeding(String heding) {
this.heding = heding;
}
public String getHeding() {
return heding;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getSummary() {
return summary;
}
public void setBer(body ber) {
this.ber = ber;
}
public body getBer() {
return ber;
}
#Override
public String toString() {
return "id:" + id + "cat_id" + cat_id + "summary" + summary + "orig_date"
+ orig_item_date + "heding" + heding;
}
}
class body {
private String bpart;
public void setBpart(String r) {
this.bpart = r;
}
public String getBpart() {
return bpart;
}
#Override
public String toString() {
return "hiii";
}
}
}
The issue is in class Doll, You have a field ct but in json catitem. Rename the field ct to catitem or if you are using Gson use #SerializedName("catitem") on filed ct and it will work.

GSON parsing in Java with unknown number of objects

I'm new to GSON and have been having trouble parsing the JSON below. The parsing works fine until it gets to the list of bills (staring at "0":). At that point I get a null reference in the resulting gson.fromJson object. If those bills were specified in a JSON array I think it would be easy, but they're not and I can't change that. What is the best way to handle this situation?
{
"status":"OK",
"masterlist":{
"session":{
"session_id":1007,
"session_name":"97th Legislature"
},
"0":{
"bill_id":446875,
"number":"HB4001"
},
"1":{
"bill_id":446858,
"number":"HB4002"
},
"2":{
"bill_id":446842,
"number":"HB4003"
},...
This is the code in my main method:
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
ResponseData response = gson.fromJson(reader, ResponseData.class);
And this is the ResponseData class:
public class ResponseData {
private String status;
private MasterList masterlist;
public static class MasterList{
private Session session;
private Bill bill; //Also tried: Map<String, String> bill;
}
public static class Session{
private String session_id;
private String session_name;
}
public static class Bill{
private String bill_id;
private String number;
}
}
You can map the object as below:
declare an object to map with json string
public class ResponseData {
private String status;
private Map<String, MasterList> masterlist;
public Map<String, MasterList> getMasterlist() {
return masterlist;
}
public void setMasterlist(Map<String, MasterList> masterlist) {
this.masterlist = masterlist;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public static class MasterList {
private String session_id;
private String session_name;
private String bill_id;
private String number;
public String getSession_id() {
return session_id;
}
public void setSession_id(String session_id) {
this.session_id = session_id;
}
public String getSession_name() {
return session_name;
}
public void setSession_name(String session_name) {
this.session_name = session_name;
}
public String getBill_id() {
return bill_id;
}
public void setBill_id(String bill_id) {
this.bill_id = bill_id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
}
And use it as below:
String data = "{\"status\":\"OK\",\"masterlist\":{ \"session\":{ \"session_id\":1007, \"session_name\":\"97th Legislature\" }, \"0\":{ \"bill_id\":446875, \"number\":\"HB4001\" }, \"1\":{ \"bill_id\":446858, \"number\":\"HB4002\" }, \"2\":{ \"bill_id\":446842, \"number\":\"HB4003\" }}}";
Gson gson = new Gson();
ResponseData response = gson.fromJson(data, ResponseData.class);
for (Iterator<Entry<String, MasterList>> it = response.getMasterlist().entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, MasterList> entry = it.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue().getSession_id());
}

converting gson to object with java

I'm trying to figure out how to use gson to convert reddit's api response to a form I can use. After some code I use
System.out.println(response.toString());
to get output (slightly edited)
{"json": {"errors": [], "data": {"modhash": "dosiom5o6abbbb758729039f04762a05778db4aeeeacd8eb4a", "cookie": "14756159,2012-08-21T12:05:05,0971bdec35d71af4073cf56ad82fb0ae7c5fe2d1"}}}
After googling around I built the following class
class GSONClass {
private Response jsonresponse;
public Response getJsonresponse() {
return jsonresponse;
}
public void setJsonresponse(Response jsonresponse) {
this.jsonresponse = jsonresponse;
}
public static class Response {
private String[] errors;
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String[] getErrors() {
return errors;
}
public void setErrors(String[] errors) {
this.errors = errors;
}
}
public static class Data {
private String modhash = "hi";
private String cookie;
public String getCookie() {
return cookie;
}
public void setCookie(String cookie) {
this.cookie = cookie;
}
public String getModhash() {
return modhash;
}
public void setModhash(String modhash) {
this.modhash = modhash;
}
}
}
Then I use:
GSONClass target = new GSONClass();
String json = gson.toJson(response.toString());
GSONClass target = gson.fromJson(json, GSONClass.class);
I'm doing something wrong because I get a "java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING" error.
You were close. Your object needed to have an attribute named json that contained both an array(errors) and an object named data that contained properties modhash and cookie. The property you were calling jsonResponse needed to be called json.
public class GSONClass {
private Response json;
public static class Response {
private String[] errors;
private Data data;
}
public static class Data {
private String modhash = "hi";
private String cookie;
}
}
And a stub/runner.
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
String response = "{\"json\": {\"errors\": [], \"data\": {\"modhash\": \"dosiom5o6abbbb758729039f04762a05778db4aeeeacd8eb4a\", \"cookie\": \"14756159,2012-08-21T12:05:05,0971bdec35d71af4073cf56ad82fb0ae7c5fe2d1\"}}}";
GSONClass target = new Gson().fromJson(response, GSONClass.class);
System.out.println(target);
}
}

Categories