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?
Related
I have one Registration Api which has error object in which it shows Errors Dynamically in Array.
This is the JsonFormat of Api :
{
"status_code": 422,
"status": "error",
"data": {
"errors": {
"password": [
"The password must be between 8 and 15 characters."
],
"mobile_no": [
"The mobile number has already been taken."
]
}
}
}
Here if a user forgot to write name then it will show username array in errors. So it changes dynamically.
My question is how I can set this type of errors in gson.I am using retrofit to call Api.
I did this in my Data class but it showing me errors.
#SerializedName("errors")
#Expose
JsonObject errorObject;
Iterator iterator=new Iterator() {
#Override
public boolean hasNext() {
Iterator keys=errorObject.keys();
if(keys.hasNext()){
}
}
#Override
public Object next() {
return null;
}
}
Please help me how can I getErrors using gson.Thank u
You can use Map to maintin the datastructure like this:
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(yourErrorsArrayHere, type);
and then just use myMap.get("your_error_key") to get the particular error.
My Code - I'm trying to return the data from JSON.
JSONObject count = new JSONObject(finalJson);
JSONArray itemsArray = count.getJSONArray("Items");
JSONObject finalObject = itemsArray.getJSONObject(0);
String record = finalObject.getString("myid");
String vocabulary = finalObject.getString("vocab");
String method = finalObject.getString("method");
return record + vocabulary + method;
JSON I'm trying to parse- Count object, Items array, etc...
{
"Count":1,
"Items":[
{
"myid":{
"S":"1"
},
"vocab":{
"S":"print a line"
},
"method":{
"S":"system.out.println"
}
}
],
"ScannedCount":1
If there is a fixed schema, you can transfer the DynamoDB JSON to JSON via a mapping template on API Gateway.
Mapping Template
#set($inputRoot = $input.path('$'))
{
"items": [
#foreach($elem in $inputRoot.Items) {
"myid": "$elem.myid.S",
"vocab": "$elem.vocab.S",
"method": "$elem.method.S"
}#if($foreach.hasNext),#end
#end
]
}
Then, you can parse the JSON String from API Gateway in your Android application into an object.
Sample parsing code
public class Items {
private List<Item> items;
//getters and setters
}
public class Item {
private String myid;
private String vocab;
private String message;
//getters and setters
}
Items items;
ObjectMapper mapper = new ObjectMapper();
jsonData = .... // from API Gateway
items = mapper.readValue(jsonData, Items.class);
Also, there is better way to get those information from API Gateway's generated android SDK. In order to do so, you need to define a Model Schema and set to the method response, then once you deploy your API change this modification, you can download an android SDK for your API.
Model Schema
{
"type": "object",
"properties": {
"items": {
"type": "array",
"item": {
"properties": {
"myid": {
"type": "string"
},
"vocab": {
"type": "string"
},
"method": {
"type": "string"
}
}
}
}
}
}
You might want to read this step by step walkthrough if you want to have more detail on how to mapping response work, and
I want to parse JSON Array and display result in listview. I have already ask in this community but didn't get helpful answer. Please give me code for this JSON.
JSON
[{
"city_id": "1",
"city_name": "Noida"
},
{
"city_id": "2",
"city_name": "Delhi"
},
{
"city_id": "3",
"city_name": "Gaziyabad"
},
{
"city_id": "4",
"city_name": "Gurgaon"
},
{
"city_id": "5",
"city_name": "Gr. Noida"
}]
URL
http://14.140.200.186/Hospital/newget_city.php
please help
As mentioned the question is too broad, just to give the approach I would take.
Build the model class in this case: City
I would advise using retrofit(http://square.github.io/retrofit/) for the network call, so build the interface
Make the network call
Add the retrieved results in a recyclerview adapter
Using Gson can do the json parsing job for you. Its easy to integrate and handy to parse json data. You simply need to create a class containing city_id and city_name.
City.java
public class City {
private String city_id;
private String city_name;
public City() {
}
public String getCityId() {
return city_id;
}
public String getCityName() {
return city_name;
}
}
Now add another class. E.g. CityList.java
import java.util.List;
public class CityList {
private List<City> cityList;
public CityList() {
}
public List<City> getCityList() {
return cityList;
}
}
Now from json string, parse the data into the CityList class.
Gson gson = new Gson();
CityList myCityList = gson.fromJson(jsonString, CityList.class);
Add the gradle dependency for Gson in build.gradle
compile 'com.google.code.gson:gson:2.3'
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.
Hi I already used GSON for parsing simple jsonobjects. But this time my response data is much complex. So I am struggling to parse that data.My data looks like :
[{"creator":"1", "users":[{"userName":"nilesh", "userAge":"25"},{"userName":"Me", "userAge":"25"}]},
{"creator":"2", "users":[{"userName":"nilesh", "userAge":"25"},{"userName":"Me", "userAge":"25"}]}
]
So I wrote one parsing class in following ways
public class UserData
{
#SerializedName("creator")
public String creator;
public List<Users> users;
public static class Users
{
#SerializedName("userName")
public String userName;
#SerializedName("userAge")
public String userAge;
}
}
But this is not working. Am I doing some thing wrong need some help regarding this parsing. thank you.
I tried to parse like this :
Gson gson = new Gson();
UserData users = gson.fromJson(result, UserData.class);
And it gives me error like this :
01-04 12:36:04.337: E/AndroidRuntime(15651): Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
It is because your JSON you posted is invalid.
It should be like this The posted json below is your json which is valid.
[
{
"creator": "1",
"users": [
{
"userName": "nilesh",
"userAge": "25"
},
{
"userName": "Me",
"userAge": "25"
}
]
},
{
"creator": "2",
"users": [
{
"userName": "nilesh",
"userAge": "25"
},
{
"userName": "Me",
"userAge": "25"
}
]
}
]
The json you have posted contains errors at following points
users [ should be "users" :[
userAge : should be "userAge":
This is what I was looking for
public class UserData
{
public String creator;
public List<Users> user;
public class Users
{
public String userName;
public String userAge;
}
}
and I parse in following manner
Gson gson = new Gson();
Type type = new TypeToken<List<UserData>>(){}.getType();
List<UserData > objList = gson.fromJson(result, type);