How to read a JSONArray from a JSONObject using GSON.
I am trying to read this JSON String:
String str = { "text" : [
{
"id": 1,
"msg":"abc"
},
{
"id": 2,
"msg":"xyz"
},
{
"id": 3,
"msg":"pqr"
}
] }
The class is:
Class A {
int id;
String msg;
// And setters and getters
}
This code does not work:
class Test {
A [] text;
}
Test t = gson.fromJson(response, Test.class);
Also
class Test {
ArrayList<A> text = new ArrayList<A>();
}
Test t = gson.fromJson(response, Test.class);
How else can i read the string using my Test class?
Please help...
Update your class
public class A {
#SerializedName("id")
int id;
#SerializedName("msg")
String msg;
// And All setter and getter
}
The values given as "JSON String" are values to initiate the A class. And they are an array of As. What might work is
A[] t = gson.fromJson(response, A[].class);
Deserializing arrays is described in the manual, 5.4 Array Examples.
Related
I have a Json like this
"data": {
"2020-05-01": {
"tanggal": "Jumat, 01\/05\/2020",
"subuh": "05:05",
"dzuhur": "12:33",
"ashar": "15:51",
"maghrib": "18:40",
"isya": "19:51"
},
"2020-05-02": {
"tanggal": "Sabtu, 02\/05\/2020",
"subuh": "05:04",
"dzuhur": "12:33",
"ashar": "15:51",
"maghrib": "18:40",
"isya": "19:52"
}
}
how can I get the Json, If the object is Date but I must have to use retrofit
Thanks for your help.
Try to use a Map:
class Data {
Map<String, MyObject> firstData;
Map<String, MyObject> secondData;
}
Where MyObject is:
class MyObject {
String tanggal;
String subuh;
String dzuhur;
String ashar;
String maghrib;
String isya;
}
My JSON like this:-
{
"status": "approved",
"work_flow": {
"id": 27,
"name": "xgfdhx",
"role": "xfhxfhg",
"user_image": null
}
}
And my GsonCode is this:-
EmployeeDTO eDTO = gson.fromJson(json, eDTO.class);
so
Log.d(TAG,"Response: "+eDTO.getStatus())-----o/p:- Approved
means I am successfully get the status but I had problem to iterate the inner JSON,
Can someone explain me or help me how to get the work_flow inner JSON data.
using GSON builder?
Try
1. Change this line EmployeeDTO eDTO = gson.fromJson(json, eDTO.class); to
EmployeeDTO eDTO = gson.fromJson(json, EmployeeDTO.class);
2. Add class EmployeeDTO.java
public class EmployeeDTO {
String status;
#SerializedName("work_flow")
WorkFlow workFlow;
}
3. Add class WorkFlow.java
public class WorkFlow {
int id;
String name;
String role;
String userImage;
}
I'm trying to parse a JSON object using retrofit 2.0 following this guide, but it doesn't work. I think it's because of a difference in JSON format.
Here is a nested JSON object with the format:
{
"SearchService": {
"list_total_count": 531,
"RESULT": {
"CODE": "INFO-001",
"MESSAGE": "SUCCESS"
},
"row": [{
"ID": "1983",
"NAME": "SAN",
"NUM": "38",
}, {
"ID": "1984",
"NAME": "DU",
"NUM": "27",
}]
}
}
Here is class code using SerializedName:
RowList.java
public class RowList {
#SerializedName("row")
#Expose
private ArrayList<Row> rows= new ArrayList<>();
public ArrayList<Row> getRows() {
return rows;
}
public void setRows(ArrayList<Row> rows) {
this.rows= rows;
}
}
Row.java
public class Row{
#SerializedName("ID")
#Expose
private String id;
#SerializedName("NAME")
#Expose
private String name;
#SerializedName("NUM")
#Expose
private String num;
/*getter setter*/
}
Read that guide.
There are two approaches to create Model class. The first way is the manual approach, which requires you to learn how to use the Gson library. The second approach is you can also auto-generate the Java classes you need by capturing the JSON output and using jsonschema2pojo
Looks like you've attempted approach one, but haven't (yet?) tried reading over the Gson documentation.
Okay, you have a Row. That covers the objects within "row": [...], so you also need objects for the following:
"SearchService": {}
"RESULT": {}
I don't think the RowList class is necessary. List<Row> is fine.
For example,
class Result {
#SerializedName("CODE")
String code;
#SerializedName("MESSAGE")
String message;
}
class SearchService {
#SerializedName("list_total_count")
long count;
#SerializedName("RESULT")
Result result;
#SerializedName("row")
private ArrayList<Row> rows= new ArrayList<>();
}
(removed #Expose for conciseness)
Then, Retrofit would use Call<SearchService>
I am facing json conversion exception. While i converting json to java object.
Here is my json
[
{
"PrefrenceId":"228f176d-d224-32d7-9bb5-6287a06a68e8",
"UserId":"327e6c64-bc90-3ae8-8f7d-72837581ca13",
"QuestionnaireId":"41f31b11-47f5-3e29-8c88-1a3615c978a7",
"Suggestions":"",
"Explanation":"",
"IsActive":true,
"IsDelete":false,
"DateCreated":"2016-11-01 09:53:00.000",
"DateUpdated":"2016-11-01 09:53:17.000"
},
{
"PrefrenceId":"52a74739-bdd3-33ac-a83f-72f60b1992b5",
"UserId":"327e6c64-bc90-3ae8-8f7d-72837581ca13",
"QuestionnaireId":"8cd5ac8e-89db-3d7b-bb2d-4e6735b245de",
"Suggestions":"",
"Explanation":"",
"IsActive":true,
"IsDelete":false,
"DateCreated":"2016-11-01 09:48:53.000",
"DateUpdated":"2016-11-01 09:53:15.000"
},
{
"PrefrenceId":"ae7fc877-b26a-34d3-a5f3-244c7e777e08",
"UserId":"327e6c64-bc90-3ae8-8f7d-72837581ca13",
"QuestionnaireId":"d3b98cde-111c-30d5-a4c9-412a76b656eb",
"Suggestions":"Camping",
"Explanation":"",
"IsActive":true,
"IsDelete":false,
"DateCreated":"2016-11-01 09:53:02.000",
"DateUpdated":"2016-11-01 09:53:19.000"
},
{
"PrefrenceId":"bcac0da7-31a6-345f-be82-ddff17c29b35",
"UserId":"327e6c64-bc90-3ae8-8f7d-72837581ca13",
"QuestionnaireId":"8fb1bda7-7ec8-3538-8aa8-ff84637764a4",
"Suggestions":"",
"Explanation":"",
"IsActive":true,
"IsDelete":false,
"DateCreated":"2016-11-01 09:53:07.000",
"DateUpdated":"2016-11-01 09:53:22.000"
},
{
"PrefrenceId":"ff46ce3c-70cb-3d25-8dbb-10e9c46d4c2d",
"UserId":"327e6c64-bc90-3ae8-8f7d-72837581ca13",
"QuestionnaireId":"3afffc17-30e4-311f-a0fc-8daa3bda6c98",
"Suggestions":"",
"Explanation":"",
"IsActive":true,
"IsDelete":false,
"DateCreated":"2016-11-01 09:53:05.000",
"DateUpdated":"2016-11-01 09:53:20.000"
}
]
My POJO classes :-
public class SurvivorZAMQuestionList implements Serializable {
public List<SurvivorZAMQuestionnaire> survivorZAMQuestionnaires;
}
public class SurvivorZAMQuestionnaire implements Serializable {
public String Suggestions;
public String PrefrenceId;
public String IsActive;
public String IsDelete;
public String DateCreated;
public String DateUpdated;
public String UserId;
public String QuestionnaireId;
public String Explanation;
}
But when i am converting json response to json it is showing following error:-
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
Can anyone tell me what i am missing in pojo class.
Any kind of held should be appreciated.
Your response is proper but your parsing is not proper. So first of all add GSON in your gradle file.
compile 'com.google.code.gson:gson:2.4'
Now use below your code for parsing your response
try {
JSONArray array = new JSONArray("put your response here");
Gson gson = new Gson();
for (int i = 0 ; i <array.length();i++)
{
SurvivorZAMQuestionnaire obj = new SurvivorZAMQuestionnaire();
obj.add(gson.fromJson(array.getJSONObject(i).toString(),SurvivorZAMQuestionnaire.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
Add your obj in list and show it :)
The Error clearly states that the Gson accepts JsonObject not JsonArray. In your case you can put the response JsonArray into a JsonObject with a key for that JsonArray and give that key as annotation in SurvivorZAMQuestionList. By this way you can easily sort this problem.
Hope this is Helpful :)
You can try to use GSON library -> compile 'com.google.code.gson:gson:2.8.0'
List<SurvivorZAMQuestionnaire> survivorZAMQuestionnaires;
...
Gson gson = new Gson();
Type listType = new TypeToken<List<SurvivorZAMQuestionnaire>>(){}.getType();
survivorZAMQuestionnaires = gson.fromJson(jsonString, listType);
Type is instance of java.lang.reflect.Type;
Parse Your Json this way,
List<SurvivorZAMQuestionnaire> survivorZAMQuestionnaires = new Gson().fromJson(json, new TypeToken<List<SurvivorZAMQuestionnaire>>() {
}.getType());
Do a gradle dependency of gson.
compile 'com.google.code.gson:gson:2.4'
Update code like this;
private void parseJSON(String jsonMessage) throws JSONException {
if (jsonMessage.startsWith("[")) {
Type type = new TypeToken<List<SurvivorZAMQuestionnaire>>()
}.getType();
List<SurvivorZAMQuestionnaire> survivorZAMQuestionnaireList =new Gson().fromJson
(jsonMessage, type);
Log.d("Print List",survivorZAMQuestionnaireList.toString());
}
}
You need List of objects not only object, because your JSON contain list of objects. How to Parse JSON Array in Android with Gson
I've used gson library for parsing json response. its working well. now i got a problem .
i've got below response from webservice. the json key value is not static, it will dynamically change.
how to write a parser class to parse the below response.
Formatted JSON:
{
"meta": {
"code": 201,
"dataPropertyName": "activity",
"currentTime": "2014-02-05 06:15:04",
"listedCount": "2"
},
"activity": [
{
"comments": [
{
"raja": {
"type": "Liked",
"userPhoto": "663.png",
"userId": "74",
"userName": {
"1_0": "longjump"
},
"postOwner": "you",
"postDetails": {
"471": {
"postImage": "972.png",
"postId": "471",
"postType": "1"
}
},
"dateTime": "2014-02-05 05:24:56",
"sameOwner": "1"
}
}
]
},
{
"follow": [
{
"you": {
"type": "follow",
"followByUserName": {
"0_0": "olivepop",
"1_0": "yadidroy",
"2_0": "chitra"
},
"followUserName": "you",
"followByUserPhoto": "242.png",
"followUserPhoto": "953.png",
"dateTime": "2014-01-09 06:50:42"
}
}
]
}
],
"notifications": [
"Activities has been retrieved successfully"
]
}
Use this parser class
Meta meta = new Meta();
ArrayList<Activity> activity = new ArrayList<ActivityParser.Activity>();
ArrayList<String> notifications = new ArrayList<String>();
public class Meta
{
String code,dataPropertyName,currentTime,listedCount;
}
public class Activity
{
ArrayList<HashMap<String, CommentsItem>> comments = new ArrayList<HashMap<String,CommentsItem>>();
public class CommentsItem
{
String type,userPhoto,userId,postOwner,dateTime,sameOwner;
HashMap<String, String> userName = new HashMap<String,String>();
HashMap<String, PostDetails> postDetails = new HashMap<String,PostDetails>();
public class PostDetails
{
String postImage,postId,postType;
}
}
ArrayList<HashMap<String, FollowItem>> follow = new ArrayList<HashMap<String,FollowItem>>();
public class FollowItem
{
String type,followUserName,followByUserPhoto,followUserPhoto,dateTime;
HashMap<String, String> followByUserName = new HashMap<String,String>();
}
}
If possible get a JSON response with all possible "Key" values and then get the POJO class auto build from below link:
POJO FOR GSON
It will automatically handle all the posibilities. But make sure the RESPONCE you are providing while generating the POJO should hold all the possible combinations of your Key [changing once].
HOPE THIS HELPS!!
Depending on your specification, you can make a Default Webservice response model.java which would be something like:
String success;
#SerializedName("error_msg")
String errorMessage;
#SerializedName("error_code")
String errorCode;
JsonObject data;
where the Parent of the object with dynamic keys would be the "data".
Use Gson, map the model class:
webserviceResponse= gson.fromJson(contentResponse,WebserviceResponse.class);
if (StringUtils.isNotEmpty(webserviceResponse.getSuccess()) &&
StringUtils.equalsIgnoreCase(webserviceResponse.getSuccess(), "success")) {
//check for the dynamic key name
JsonObject job = webserviceResponse.getData();
dynamicallyDefinedKeyClass= gson.fromJson(job.get("dynamicKeyValue"), DynamicallyDefinedKeyClass.class);
}
Will edit my answer on question edit, in any way if it can help
Just a suggestion - raja, you etc. can be values for a key - name or commentsBy ? Where are you getting this response from?