Parsing JSON file in Android Application - android

How would I parse the following string in Android?
{
"C1": {
"name": "first name",
"address": "first address",
"lat": 36.072111,
"lng": 34.732112
},
"C2": {
"name": "second name",
"address": "second address",
"lat": 32.02132,
"lng": 34.000002
},
"C3": {
"name": "third name",
"address": "third address",
"lat": 37.05435,
"lng": 34.75703
}
}
I can't understand. Is it an objects inside of an object structure? How would this be parsed? How do I find how many objects I have?

Well, got it. the solution is to first get the names of the inner-objects:
JONObject json = new JSONObject(jsonString);
JSONArray namesArray = json.names();
which will give you an JSONArray of the existing objects inside.
Then run on it's objects to get each one of them:
for (int i = 0 ; i < namesArray.length() ; i ++)
{
currentObject = json.getJSONObject(namesArray.get(i).toString());
Log.d("TAG", "currentObject : "+currentObject.toString());
addCurrentObjectShopToObjectsListUsingGson(currentObject,objectsList);
}

You can use JSONObject to extract the contents of the structure.
An example can be shown below:
You can retrieve a JSONArray from your string with
JSONObject json = new JSONObject(jsonString);
JSONArray myArray = json.getJSONArray(ARRAY_NAME_HERE);
After doing so, you can extract the name of a person with
JSONObject person = myArray.getJSONObject(0); // retrieve the first person
String name = person.getString("name"); // get the person's name
Reference:
http://developer.android.com/reference/org/json/JSONObject.html

The string you've shown contains an outer object with 3 inner objects. Suppose you want to get C1.name. You would do this:
JSONObject root = new JSONObject(yourString);
JSONObject c1 = root.getJSONObject("C1");
String name = c1.getString("name");
However, I should point out one other thing, which is that the original string you are using is odd because it suggests that what you really want is an array. The code to parse would be different, of course, and involve JSONArray, but I think a better representation would look like this:
[
{"name":"first name","address":"...","lat":"...","lng":"..."},
{"name":"second name"...},
{"name":"third name"...}
]
So in this case, the outermost container is a JSONArray, not an object.

You need a "model" object that looks like this: (provided the hash is static).
public class TheCs extends BaseModel {
public OneC c1;
public OneC c2;
public OneC c3;
}
public class OneC extends BaseModel {
public String name;
public String address;
public float lat, lng;
}
public class BaseModel implements Serializable {
private static final long serialVersionUID = 1L;//use a random number here
}
Now when parsing with Gson, pass TheCs.class as the type.
If the Hash is not static you could (and Gson will do the right thing as far as I can remember), do something like:
public class TheCs extends BaseModel {
public List<OneC> someHash;
}

Related

Getting element of JSON object when key isn't the same [Android]

I want to learn a bit more about android and wanted to create an app that will track the price of cryptocurrencies. I choosed this API: https://www.cryptocompare.com/api/#introduction
My problem is the following: When I want to get the list of all the coin the JSON response looks like this:
{
"Response": "Success",
"Message": "Coin list succesfully returned!",
"BaseImageUrl": "https://www.cryptocompare.com",
"BaseLinkUrl": "https://www.cryptocompare.com",
"Data": {
"42": {
"Id": "4321",
"Url": "/coins/42/overview",
"ImageUrl": "/media/19984/42.png",
"Name": "42",
"CoinName": "42 Coin",
"FullName": "42 Coin (42)",
"Algorithm": "Scrypt",
"ProofType": "PoW",
"FullyPremined": "0",
"TotalCoinSupply": "42",
"PreMinedValue": "N/A",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "34"
},
"365": {
"Id": "33639",
"Url": "/coins/365/overview",
"ImageUrl": "/media/352070/365.png",
"Name": "365",
"CoinName": "365Coin",
"FullName": "365Coin (365)",
"Algorithm": "X11",
"ProofType": "PoW/PoS",
"FullyPremined": "0",
"TotalCoinSupply": "2300000000",
"PreMinedValue": "299000000",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "916"
},
(here is the URL I use (https://www.cryptocompare.com/api/data/coinlist/)
I want to keep all the informations about the coin (everything from "Data") but the key isn't the same.
How can I get those informations to create my differents coins?
Thank's in advance
You can use JSONObject#names() to get all the keys as JSONArray and loop the JSONArray.
JSONObject data = response.getJSONObject("Data");
JSONArray array = data.names(); // contains all the keys inside Data
// now loop the array
for (int i = 0; i < array.length(); i++ ) {
String key = array.getString(i); // 42 or 365 for your example code
JSONObject obj = data.getJSONObject(key); // contains the JSONObject of the key 42 or 365
}
Another way is to use JSONObject#keys() but that uses Iterator and hasNext() for iteration which is less performance efficient than the above normal for loop approach in Android.
The accepted answer is fine. I would like to show the way of parsing using Gson from your JSON. Here's how it can be parsed using Gson.
You need to have two classes.
Here's your APIResponse.java
public class APIResponse {
public String Response;
public String Message;
public String BaseImageUrl;
public String BaseLinkUrl;
public HashMap<String, DataObject> Data;
}
And the DataResponse class should look like
public class DataObject {
public String Id;
public String Url;
public String ImageUrl;
public String Name;
public String CoinName;
public String FullName;
public String Algorithm;
public String ProofType;
public String FullyPremined;
public String TotalCoinSupply;
public String PreMinedValue;
public String TotalCoinsFreeFloat;
public String SortOrder;
}
Now its pretty easy.
Type type = new TypeToken<APIResponse>(){}.getType();
APIResponse response = new Gson().fromJson(yourJsonString, type);
Now iterate the HashMap for getting the keys and corresponding values.
You can fetch all the keys and iterate as below
try {
JSONObject dataObj = obj.getJSONObject("Data"); //obj is the parent json object.
Iterator<?> keys = dataObj.keys();
while(keys.hasNext()) {
JSONObject coinObj = dataObj.getJSONObject(keys.next().toString());
}
} catch (JSONException e) {
e.printStackTrace();
}

Nested Json parsing using Gson

I have tried to parse this JSON using gson but I couldn’t.
Can anyone help me to parse this JSON using gson?
JSON:
{
"status": "ok",
"results": {
"favourites": [
{
"id": "UB3172",
"name": "Masdar Headquarters"
},
{
"id": "UB1438",
"name": "Guggenheim Abu Dhabi on Saadiyat Island"
},
{
"id": "UB4838",
"name": "Watani Residential Development in Abu Dhabi - 600 Villas and 48 Buildings"
},
{
"id": "UB4795",
"name": "Two Mosques in Mohammed Bin Zayed City"
},
{
"id": "UB1274",
"name": "2 Workers Residential City at Al Ain Industrial City"
}
]
}
}
I tried this one for JSON parser class:
public class ProjectList {
public String status;
public String results;
public class Favourites{
public String id;
public String name;
}
}
In MainActivit
Reader reader = new InputStreamReader(result);
Gson gson=new Gson();
List<ProjectList.Favourites> fav=new ArrayList<ProjectList.Favourites>();
fav=Arrays.asList(gson.fromJson(reader, ProjectList.Favourites.class));
Create a POJO class as follows
class MyResponse {
public String status;
public Result results;
public static class Favourites {
public String id;
public String name;
}
public static class Result {
public List<Favourites> favourites;
}
}
and pass it to gson as
MyResponse response = new Gson().fromJson(yourResponse, MyResponse.class);
idea is that maintain the hierarchy of key-value pairs with appropriate POJO's
You can generate your pojos here : http://www.jsonschema2pojo.org/
Sometimes gson cannot convert your objects from json. In this case you have to write your own deserializer and use it with gson builder.
Edit: If you use proguard before release your project (if you set proguard to change your pojos variable names) gson cannot match class variable names, json names so it cannot convert your objects. You have to add #SerializedName("your_variable_name") annotaion.
Try this way,hope this will help you to solve your problem.
String jsonRespone = "{\"status\":\"ok\",\"results\":{\"favourites\":[{\"id\":\"UB3172\",\"name\":\"Masdar Headquarters\"},{\"id\":\"UB1438\",\"name\":\"Guggenheim Abu Dhabi on Saadiyat Island\"},{\"id\":\"UB4838\",\"name\":\"Watani Residential Development in Abu Dhabi - 600 Villas and 48 Buildings\"},{\"id\":\"UB4795\",\"name\":\"Two Mosques in Mohammed Bin Zayed City\"},{\"id\":\"UB1274\",\"name\":\"2 Workers Residential City at Al Ain Industrial City\"}]}}";
String status;
ArrayList<HashMap<String,String>> favouritesList = new ArrayList<HashMap<String, String>>();
try{
JSONObject responseJson = new JSONObject(jsonRespone);
status = responseJson.getString("status");
JSONArray favouriteJsonArray = responseJson.getJSONObject("results").getJSONArray("favourites");
for (int i=0;i<favouriteJsonArray.length();i++){
HashMap<String,String> favourite = new HashMap<String, String>();
favourite.put("id",favouriteJsonArray.getJSONObject(i).getString("id"));
favourite.put("name",favouriteJsonArray.getJSONObject(i).getString("name"));
favouritesList.add(favourite);
}
System.out.print("status : "+status);
for (HashMap<String, String> favourite : favouritesList) {
System.out.print("id : "+favourite.get("id"));
System.out.print("name : "+favourite.get("name"));
}
}catch (Throwable e){
e.printStackTrace();
}

Parsing JSON file with different number of keys

My JSON file contains strings with the same keys but some of them doens't appear for some strings. For example:
{
"city": "CB1 2BH Cambridge",
"addr": "Devonshire Road 1",
"title": "Devonshire Arms",
"phone": "+44 1223 6610"
},
{
"city": "E8 1JH London",
"addr": "Amhurst Road 90",
"title": "Pembury Tavern",
"web": "http://www.individualpubs.co.uk/pembury/"
},
{
"web": "http://bandholmhotel.dk/",
"title": "Bandholm Hotel",
},
{
"city": "00100 Helsinki",
"addr": "Pohjoinen Rautatiekatu 23",
"title": "Helkan Baari",
"country": "FI"
},
How to correctly parse it in android?
Considering this is your JSONArray,
Try to do as following,
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObj = (JSONObject) jsonProductArray.getJSONObject(i);
String city = jObj.optString("city", "cityDefaultValue");
String addr = jObj.optString("addr", "addDefaultValue");
String title = jObj.optString("title", "titleDefaultValue");
String phone = jObj.optString("phone", "phoneDefaultValue");
}
One possible solution can be to have a modal class and use Gson library to parse the Json.
You can set some default values in your modal class, for keys whose value is not found in Json
Create an model class with the key of the json and parse it to the model class using gson.
A a = gson.fromJson(jsonRes.toString(),A.class);
here A is your model class and a is the instance of A
You can use Gson library.
Create something like that
class SomeObjects {
#SerializedName("city")
private String mCity;
#SerializedName("addr")
private String mAddres;
...
}
and in then
SomeObject obj = new Gson.fromJson(jsonString, SomeObject.class);
You also can sirialize right into array

Android code For Following JSON Pattern

Want Android Code For Following JSON Format...Bit Confused How to fetch value of array For Following Pattern..
{
"params": [
{
"answer_data_all": [
{
"id": "5",
"question_id": "14"
}
],
"form_data_all": [
{
"id": "1",
"name": "form 1"
}
]
}
]
}
You just have some nested JSONArray and JSONObject. Assuming you have this response in string format all you have to do is create JSONObject from that string and then extract what you need. As someone mentioned [ ] encloses JSONArray while { } encloses JSONObject
JSONObject mainObject = new JSONObject(stringResponse);
JSONArray params = mainObject.getJSONArray("params"); //title of what you want
JSONObject paramsObject = params.getJSONObject(0);
JSONArray answerData = paramsObject.getJSONArray("answer_data_all");
JSONArray formData = paramsObject.getJSONArray("form_data_all");
String id = formData.getJSONObject(0).getString("id");
You should be able to extract all the values doing something like this. Although I will say I think the formatting is odd. You're using single member arrays that just contain other objects. It would make much more sense to either use one array to hold all the object or just separate JSONObject. It makes it much easier to read and easier to parse.
Parsing a JSON is fairly simple. You could use GSON library by Google for example. Below is an example I wrote for your object/model:
class MyObject{
ArrayList<Params> params;
class Params {
ArrayList<AnswerData> answer_data_all;
ArrayList<FormData> form_data_all;
class AnswerData {
String id;
String question_id;
}
class FormData {
String id;
String name;
}
}
}
And then get an instance of your object with:
MyObject myObject = (MyObject) (new Gson()).toJson("..json..", MyObject.class);
JSONArray feed = feedObject.getJSONArray("params");
for(int i = 0; i<feed.length(); i++){
JSONArray tf = feed.getJSONArray(i);
for (int j = 0; j < tf.length(); j++) {
JSONObject hy = tf.getJSONObject(j);
String idt = hy.getString("id");
String name = hy.getString("name");
}
}
**NOTE: the 'feedObject' variable is the JSONObject you are working with..Although this your type of JSON feed is kinda mixed in terms of string names and all but this should do for now..

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