Nested Json parsing with GSon - android

How to parse below Json Response with google Gson.?
{
"rootobject":[
{
"id":"7",
"name":"PP-1",
"subtitle":"name-I",
"key1":"punjab",
"key12":"2013",
"location":"",
"key13":"0",
"key14":"0",
"key15":"0",
"result_status":null
},
{
"id":"7",
"name":"PP-1",
"subtitle":"name-I",
"key1":"punjab",
"key12":"2013",
"location":"",
"key13":"0",
"key14":"0",
"key15":"0",
"result_status":null
},
{
"id":"7",
"name":"PP-1",
"subtitle":"name-I",
"key1":"punjab",
"key12":"2013",
"location":"",
"key13":"0",
"key14":"0",
"key15":"0",
"result_status":null
},
{
"id":"7",
"name":"PP-1",
"subtitle":"name-I",
"key1":"punjab",
"key12":"2013",
"location":"",
"key13":"0",
"key14":"0",
"key15":"0",
"result_status":null
}
]
}

I'd create objects to "wrap" the response, such as:
public class Response {
#SerializedName("root_object")
private List<YourObject> rootObject;
//getter and setter
}
public class YourObject {
#SerializedName("id")
private String id;
#SerializedName("name")
private String name;
#SerializedName("subtitle")
private String subtitle;
//... other fields
//getters and setters
}
Note: use #SerializedName annotation to follow naming conventions in your Java attribute while matching the names in the JSON data.
Then you just parse the JSON with your Reponse object, like this:
String jsonString = "your json data...";
Gson gson = new Gson();
Response response = gson.fromJson(jsonString, Response.class);
Now you can access all the data in your Response object using getters and setters.
Note: your Response object may be used to parse different JSON responses. For example you could have JSON response that don't contain the id or the subtitle fields, but your Reponseobject will parse the response as well, and just put a null in this fields. This way you can use only one Responseclass to parse all the possible responses...
EDIT: I didn't realise the Android tag, I use this approach in a usual Java program, I'm not sure whether it's valid for Android...

You can try this hope this will work
// Getting Array
JSONArray contacts = json.getJSONArray("rootobject");
SampleClass[] sample=new SampleClass[contacts.length]();
// looping through All
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
sample[i].id = c.getString("id");
sample[i].name = c.getString("name");
sample[i].email = c.getString("subtitle");
sample[i].address = c.getString("key1");
sample[i].gender = c.getString("key12");
sample[i].gender = c.getString("location");
sample[i].gender = c.getString("key13");
sample[i].gender = c.getString("key14");
sample[i].gender = c.getString("key15");
sample[i].gender = c.getString("result_status");
}

Related

how to check value in JSON

i have this JSON i want check in this JSON has "song" or "fun" and then get value and key "price":
{
"has_error": false,
"response": {
"song": {
"price": "2000"
},
"jok": {
"price": "free_for_now"
}
},
"state_code": 200
}
JSONObject class have a has a method.
Ref Link : http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
Returns true if this object has a mapping for the name. The mapping may be NULL.
for example
if (json.has("song")) {
JSONObject song = jsonObject.getJSONObject("song");
}
if (json.has("fun")) {
JSONObject fun = jsonObject.getJSONObject("fun");
}
Using the gson only thing you must to do is to create a java class to mapping your json string.
class ModelObject{
boolean has_error;
Response response; // here you have the two objects: Song (with price attribute) and Jok (with price attribute); for these you must create another two classes
int status_code;
}
class Response{
Song song;
Jok jok;
}
class Song{
String price;
}
class Jok{
String price;
}
Be careful to use the same name for every attribute and class name and also generate getters and setters
Then you must use import GSON in your gradle file:
compile 'com.google.code.gson:gson:2.2.4'
Finally only thing you must to do is to use the methods from gson:
final Gson gson = new Gson();
//to deserialize
ModelObject obj = gson.fromJson(yourJson, ModelObject.class);
//to serialize
String toJson = gson.toJson(obj);
In obj you have all information to handle...
use this and right work
JSONObject jsonObject = new JSONObject(response).getJSONObject("response");
if (jsonObject.has("song")) {
JSONObject song = jsonObject.getJSONObject("song");
}

android: Retrieve values from nested JSON object into List type

I have a nested JSON array from which I need to retrieve values of all Usernames nested within Friends.
{
"Friends": [
{"Username": "abc"},
{"Username": "xyz"}
]
}
After I get all the usernames, I want to store it in a List that I will use with an adapter and ListView.
FriendList.java:
public class FriendList
{
#SerializedName("Username")
private String username;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
}
This is the code that I have written so far:
if (httpResult != null && !httpResult.isEmpty()) //POST API CALL
{
Type listType = new TypeToken<List<FriendList>>() {}.getType();
List<FriendList> friendList = new Gson().fromJson(httpResult, listType);
FLCustomAdapter adapter = new FLCustomAdapter(getActivity(), friendList);
mainFriendsListView.setAdapter(adapter);
}
However, an error occurs: Failed to deserialize Json object.
Please suggest, what additions/changes should be made to it, so that I can retrieve nested JSON values into a list?
First of all, You have to understand the strucure of this Json.
You can see, it contains
1 . A json object
2 . This json object contains a json array which can include several different json objects or json arrays.
In this case, it contains json objects.
Parsing:
Get the Json Object first
try{
JSONObject jsonObject=new JSONObject(jsonResponse);
if(jsonObject!=null){
//get the json array
JSONArray jsonArray=jsonObject.getJSONArray("Friends");
if(jsonArray!=null){
ArrayList<FriendList> friendList=new ArrayList<FriendList>();
//iterate your json array
for(int i=0;i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
FriendList friend=new FriendList();
friend.setUserName(object.getString(Username));
friendList.add(friend);
}
}
}
}
catch(JSONException ex){
ex.printStackTrace();
}
hope, it will help you.
Solution with GSON.
You need to two class to parse this.
FriendList and UsernameDao.
public class UsernameDao {
#SerializedName("Username")
private String username;
//get set methods
}
Simple Json Parsing would be like this
JSONObject params=new JSONObject(httpResult);
JSONObject params1=params.getJsonObject("Friends");
JsonArray array=params1.getJsonArray();
for(int i=0;i<array.length();i++)
{
String userName=array.getJsonObject(i).getString("UserName");
// Do whatever you want to do with username
}
Following code works good without any use of GSON , Please try .
String jsonString = "Your Json Data";
JSONObject jsonRootObject = new JSONObject(jsonString );
JSONArray friendsArray = jsonRootObject .getJSONArray("Friends");
ArrayList<FriendList > friendsList = new ArrayList<FriendList >();
for(int friendsLen = 0 ;friendsLen < friendsArray .length() ; friendsLen ++){
FriendList userNameObj = new UserName();
JSONObject jsonObj = jsonRootObject.getJSONObject(friendsLen ) ;
String Username = jsonObj.getString("Username");
userNameObj .setUserName(Username );
friendsList .add(userNameObj );
}
Now friendsList the list which you want .
List<FriendList> friendList = new Gson().fromJson(httpResult, listType);
This cannot work because it expects your whole JSON document to be just an array of FriendList element (by the way, why "FriendList"?): [{"Username": "abc"},{"Username": "xyz"}] -- this is what can be parsed by your approach.
The easiest solution to fix this (apart from harder to implement but more efficient streamed reading in order to peel of possible unnecessary properties) is just creating a correct mapping:
final class Wrapper {
#SerializedName("Friends")
final List<Friend> friends = null;
}
final class Friend {
#SerializedName("Username")
final String username = null;
}
Now deserialization is trivial and you don't have to define a type token because Gson has enough information for the type from the Wrapper.friends field:
final Wrapper wrapper = gson.fromJson(response, Wrapper.class);
for ( final Friend friend : wrapper.friends ) {
System.out.println(friend.username);
}
Output:
abc
xyz
Change List<FriendList> friendList = new Gson().fromJson(httpResult, listType);
to
FriendList friends = new Gson().fromJson(httpResult, listType);
List<Friend> friends = friends.list;
Updated FriendList.java as mentioned below
FriendList.java
public class FriendList
{
#SerializedName("Friends")
public List<Friend> list;
}
Friend.java
public class Friend
{
#SerializedName("Username")
private String username;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
}

Which is the best way to parse JSON data in Android?

I have JSON data to parse. The structure is not fixed, and sometimes it comes as a single string and other times as an array.
Currently, we are using the GSON library for parsing JSON, but are facing problems when it comes as an array.
For example:
1. {"msg":"data","c":300,"stat":"k"}
2. {
"msg": [
" {\"id\":2,\"to\":\"83662\",\"from\":\"199878\",\"msg\":\"llll\",\"c\":200,\"ts\":1394536776}"
],
"c": 200,
"stat": "k",
"_ts": 1394536776
}
In the example above, sometimes I get msg as a string and sometimes as an array.
Can anyone help me? If I decide to use JSON parsing, it will be very tedious because I have around 20+ API to parse and each API contains a mininum of 50 fields.
You can use JSONObject and JSONArray classes instead of GSON to work with JSON data
for the first example
String jsonStr = "{\"msg\":\"data\",\"c\":300,\"stat\":\"k\"}";
JSONObject jsonObj = new JSONObject(jsonStr);
String msg = jsonObj.getString("msg");
Integer c = jsonObj.getInteger("c");
String stat = jsonObj.getString("stat");
For the second example
String jsonStr = ... // "your JSON data";
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonArr = jsonObj.getJSONArray("msg");
JSONObject arrItem = jsonArr.getJSONObject(0);
//and so on
Also JSONObject class have method opString, opArray which does not throw exception if data you trying to get is not exist or have a wrong type
For example
JSONArray arr = jsonObj.optJSONArray("msg");
JSONObject msg = null;
if (arr != null) {
msg = arr.getJSONObject(0)
} else {
msg = jsonObj.getJSONObject("msg");
}
You can use Google GSON lib for directly parse the json to class object. This is easy and accurate.Okay do one thing both time code is different, if the code is 300 directly parse the json object without GSON. if the code is 200 the use the GSON (Define the similar java class)
String c= json.getString("c");
if(c.equals("300")
String message = status.getString("msg");
There are two ways to parce JSON.
Manually using Android OS JSON Parser Android JSON Parsing And Conversion
Using GSON Library [Library] (https://code.google.com/p/google-gson/downloads/list). This easy to handle if you know all the parameters and models of json response.
Refer the code snippet below to deserialize your json using Google's Gson library without exceptions.
String jsonStr = "your json string ";
Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
JsonElement elem = jsonObj.get("msg");
if(elem.isJsonArray()) { //**Array**
ArrayList<MyMessage> msgList = gson.fromJson(elem.toString(), new TypeToken<List<MyMessage>>(){}.getType());
} else if(elem.isJsonObject()) { //**Object**
Note note = gson.fromJson(elem.toString(), MyMessage.class);
} else { //**String**
String note = elem.toString();
}
MyMessage class
public class MyMessage {
String to;
String from;
String msg;
int id;
int c;
long ts;
// Setters and Getters
}

Parse Irregular JSON format in android

Hello friends i have following JSON foramt
{
"Communities": [],
"RateLog": { "83": 5,"84": 4, "85": 5,"92": 5,"93": 4,"94": 5,"95": 5,"97": 5,"99": 4,"100": 5,"102": 5,"103": 5,"104": 5,"105": 5,"106": 5,"108": 4,"109": 4,"110": 4,"111": 5,"112": 4,"113": 4,"114": 4,"115": 5,"116": 5,"117": 5,"118": 4,"119": 5, "120": 5,"121": 4,"122": 5,"123": 4,"124": 4,"125": 4,"126": 5, "142": 5,"1150": 4, "1151": 4,"1152": 4, "1153": 4,"1154": 4, "1155": 4,"1156": 4, "1158": 5}
}
so how can i parse it any idea?
You can turn it into legal JSON by enclosing it in braces. So if you have the string:
var badJSON = '"RateLog" : { "1156": 4, ... }';
You can do this:
var goodJSON = '{' + badJSON + '}';
var parsed = JSON.parse(goodJSON);
EDIT: The above answer was before your edit. With the new format, the string is valid JSON, so simply call JSON.parse() and pass the string to get the corresponding object structure.
You must improve your json format like this :
"RateLog":[
{
id1:1156
id2:4
{
id1:1155
id2:4
}
{
id1:1155
id2:4
}
..]
JSONObject json = new JSONObject(jsonString);
JSONArray array = json.getJSONArray("Communities");
for (int i = 0; i < array.length(); i++) {
// do stuff
}
JSONObject rateJson = json.getJSONObject("RateLog");
rateJson.getInt("83"); //Will return 5
.
.
.
for more got through this tutorial
http://www.mkyong.com/java/json-simple-example-read-and-write-json/
You can use Google's Gson library to parse your response.
Using POJO class
String jsonString = "Your JSON string";
Pojo pojo = new Gson().fromJson(jsonString, Pojo.class);
class Pojo {
ArrayList<String> Communities;
HashMap<String, Integer> RateLog;
//Setters and Getters
}
Without using POGO class
Gson gson = new Gson();
String jsonString = "Your JSON string";
JsonObject jsonObj = gson.fromJson(jsonString, JsonElement.class).getAsJsonObject();
HashMap<String, Integer> RateLog = gson.fromJson(jsonObj.get("RateLog").toString(), new TypeToken<HashMap<String, Integer>>(){}.getType());
You can iterate through RateLog HashMap to get key, value pairs.

Parse a JSON object value (an Array), not the object

I'm developing an Android application that connects with Facebook using Springframework Android rest client.
With this URL:
https://graph.facebook.com/me/friends?access_token=AUTH_TOKEN
Facebook API returns:
{
"data": [
{
"name": "Friend1",
"id": "123456"
}
]
}
I want to parse the data[] values, as an array:
[
{
"name": "Friend1",
"id": "123456"
}
]
And get a FacebookFriend[].
How can I do it with GSON?
First, you'd need a FacebookFriend class (using public fields and no getters for simplicity):
public class FacebookFriend {
public String name;
public String id;
}
If you created a wrapper class such as:
public class JsonResponse {
public List<FacebookFriend> data;
}
Life becomes far simpler as you can simply do:
JsonResponse resp = new Gson().fromJson(myJsonString, JsonResponse.class);
And be done with it.
If you don't want to create an enclosing class with a data field, you'd use Gson to parse the JSON, then extract the array:
JsonParser p = new JsonParser();
JsonElement e = p.parse(myJsonString);
JsonObject obj = e.getAsJsonObject();
JsonArray ja = obj.get("data").getAsJsonArray();
(You can obviously chain all those methods, but I left them explicit for this demonstration)
Now you can use Gson to map directly to your class.
FacebookFriend[] friendArray = new Gson().fromJson(ja, FacebookFriend[].class);
That said, honestly it's better to use a Collection instead:
Type type = new TypeToken<Collection<FacebookFriend>>(){}.getType();
Collection<FacebookFriend> friendCollection = new Gson().fromJson(ja, type);
It seems, your array contain object.
you can parse it in following way.
JsonArray array = jsonObj.get("data").getAsJsonArray();
String[] friendList = new String[array.size()];
// or if you want JsonArray then
JsonArray friendArray = new JsonArray();
for(int i=0 ; i<array.size(); i++){
JsonObject obj = array.get(i).getAsJsonObject();
String name = obj.get("name").getAsString();
friendList[i] = name;
// or if you want JSONArray use it.
friendArray.add(new JsonPrimitive(name));
}

Categories

Resources