JSON Conversion Exception to java object - android

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

Related

how to get json by retrofit if serialize is date

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;
}

How to parse inner JSON using GSON builder

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;
}

How to send Array of Objects in retrofit Android?

I have an below array of objects to be passed in the service call.
[
{
"ParkingSpace": {
"sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385fc250cf2497dfe5679d1"
}
},
{
"ParkingSpace": {
"sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385ff2f0cf2497dfe567c0c"
}
},
{
"ParkingSpace": {
"sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385fd700cf2e65ecf6330c6"
}
}, {
"ParkingSpace": {
"sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385fefe0cf2497dfe567bee"
}
}, {
"ParkingSpace": {
"sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385ff690cf2497dfe567c3f"
}
}, {
"ParkingSpace": {
"sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.55e972d21170d0c2fd7d15b1"
}
}]
I am trying like below:
private String generateParkingspaceBody(final List<String> listOfsIds) {
//sids array
JSONArray sidsArray = new JSONArray();
for (String sId: listOfsIds) {
//creating sidObject and object
JSONObject sIdObject = new JSONObject();
JSONObject object = new JSONObject();
try {
sIdObject.put("sid", sId);
object.put("ParkingSpace",sIdObject);
sidsArray.put(object);
} catch (JSONException e) {
CPALog.e(TAG,e.getMessage());
}
}
return sidsArray.toString();
}
Sending this string into the service call like:
Response getNearByParkingSpaces(#Header("Authorization") String accessToken,
#Header("Content-Type") String contentType,
#Body String arrayOfSids);
But in request showing in the logact is :
"[{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}}]"
Please help me, how to send this request?
Thanks in advance.
You don't need to convert your object to a JSONArray, Retrofit will do it automatically for you.
Simply change your API method declaration to:
#Headers({
"Content-type: application/json"
})
Response getNearByParkingSpaces(#Header("Authorization") String accessToken,
#Body List<String> arrayOfSids);
I encounter same issue solve this by adding this dependencies:
implementation 'com.squareup.retrofit2:converter-scalars:$version'
There are multiple existing Retrofit converters for various data formats. You can serialize and deserialize Java objects to JSON or XML or any other data format and vice versa. Within the available converters, you’ll also find a Retrofit Scalars Converter that does the job of parsing any Java primitive to be put within the request body. Conversion applies to both directions: requests and responses.
https://futurestud.io/tutorials/retrofit-2-how-to-send-plain-text-request-body
then you can use your generateParkingspaceBody as value to post.
generateParkingspaceBody.toString() as your request body

Read JSONArray from JSONObject using GSON Android

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.

Gson parser class for dynamic json key value - Android

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?

Categories

Resources