How do i parse json object and json array in android? [duplicate] - android

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I am developing an app using json api and want to implement following format api into my app. How do i implement this in my project using android studio 2.3?
{
"getdetailsasanas": [
{
"asanaid": 1,
"asananame": "Half easy gas release pose",
"duration": 1,
"imageurl": "http://www.yogapoint.com/iOS/images/half-easy-gas-release-pose.jpg",
"imageversion": 2,
"audiourl": "http://www.yogapoint.com/iOS/audio/half-easy-gas-release-pose.mp3",
"audioversion": 1,
"videourl": "NULL",
"videoversion": 0,
"StepsForAsana": [
{
"stepnumber": 1,
"stepdesc": "Step 1",
"stepimg": "http://www.yogapoint.com/iOS/images/asana-step/half-easy-gas-release-pose-step1.jpg",
"stepimgeversion": 0,
"imgethumbversion": 1,
"imgethumburl": "http://www.yogapoint.com/iOS/images/asana-step/half-easy-gas-release-pose-step1-tb.jpg"
},
{
"stepnumber": 2,
"stepdesc": "Step 2",
"stepimg": "http://www.yogapoint.com/iOS/images/asana-step/half-easy-gas-release-pose-step2.jpg",
"stepimgeversion": 0,
"imgethumbversion": 1,
"imgethumburl": "http://www.yogapoint.com/iOS/images/asana-step/half-easy-gas-release-pose-step2-tb.jpg"
}
]
}
]
}

You can use JSONObject its default supplied with android SDK:
String json = "some JSON";
JSONObject jsonObject = new JSONObject(json);
Than you can use methods like
getBoolean(String key)
getDouble(String key)
etc
Or you can use google gson library which is in my opinion better, but you will need to include it as dependency in gradle.
There is github for the Gson.
There is Gson API

Use Gson library . Best way to parse the responses.Your can user GsonFormat plugin to generate the model for response.

Have a look on gson. It's a easy serializer for json.

It's my pleasure to answer your question.
You can do like this.
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("getdetailsasanas");
for (int i = 0; i < jsonArray.length(); i++) {
String asanaid = jsonArray.getJSONObject(i).getString("asanaid");
String asananame = jsonArray.getJSONObject(i).getString("asananame");
String duration = jsonArray.getJSONObject(i).getString("duration");
String imageurl = jsonArray.getJSONObject(i).getString("imageurl");
String imageversion = jsonArray.getJSONObject(i).getString("imageversion");
String videourl = jsonArray.getJSONObject(i).getString("videourl");
String videoversion = jsonArray.getJSONObject(i).getString("videoversion");
JSONArray StepsForAsanaArray = jsonArray.getJSONObject(i).getJSONArray("StepsForAsana");
for (int j = 0; j < StepsForAsanaArray.length(); j++) {
String stepnumber = jsonArray.getJSONObject(j).getString("stepnumber");
String stepdesc = jsonArray.getJSONObject(j).getString("stepdesc");
String stepimg = jsonArray.getJSONObject(j).getString("stepimg");
String stepimgeversion = jsonArray.getJSONObject(j).getString("stepimgeversion");
String imgethumbversion = jsonArray.getJSONObject(j).getString("imgethumbversion");
String imgethumburl = jsonArray.getJSONObject(j).getString("imgethumburl");
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Use like with this code:
JSONArray getdetailsasanas = new JSONArray(stringData);
for (int p = 0; p < getdetailsasanas.length(); p++) {
try {
JSONObject data = getdetailsasanas.getJSONObject(p);
JSONObject asanaid = data.getJSONObject("asanaid");
JSONObject stepnumber = data.getJSONObject("stepnumber");
JSONObject stepnumber = data.getJSONObject("stepnumber");
//get data from objetcs
String asananame = asanaid.getString("asananame");
int duration = asanaid.getInt("duration");
String imageurl = asanaid.getString("imageurl");
} catch (JSONException e) {
e.printStackTrace();
}
}

Related

Android: get child of Object [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
My code is :
Object value = tasks.get(key);
result value is : [{"name":"one","family":"yes"},{"name":"two","family":"no"}]
Now i want get child of value in foreach
foreach(...){
String name = ...
String family = ...
}
Your value is in JSONArray format.
Use this:
JSONArray values = new JSONArray((String) tasks.get(key)); // or alternative task.getString(key)
for (int i = 0; i < values.length(); i++) {
JSONObject entry = values.getJSONObject(i);
String name = entry.getString("name");
String family = entry.getString("family");
}
Step 1: Convert Object instance into String
String response = (String) value;
Step 2: Feed the String instance into JsonArray
//don't forget to caught JSONException here
JsonArray array = new JsonArray(response);
Step 3:
Iterate through JsonArray and get values from each JsonObject
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
//get values here
String name = object.getString("name");
String family = object.getString("family");
}
Now, the whole code should look like this
try {
JSONArray array = new JSONArray("");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String name = object.getString("name");
String family = object.getString("family");
}
} catch (JSONExceptione) {
//do something..
}
Important
If you still don't know what happened, this whole process is called JSON parsing. Learn about it.
Object itself not containig fields or something, you have to create pojo (just if you want clean and resuseble code) in order to get fields from it, for example, using Gson
Add dependencies:
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
Add pojo:
public class Pojo{
#SerializedName("name")
#Expose
private String name;
#SerializedName("family")
#Expose
private String family;
}
Convert:
Gson gson = new Gson();
Pojo pojo = gson.fromJson(jsonObject.toString(), Pojo.class);

I am facing some problems with json parsing

{"success":"true",
"groups":[
{
"groupId":"c20f2353-1f13-4ea0-8283-ghhjc4dcc725251b",
"name":"hb",
"description":"hjj",
"image":null,
"membersCount":1,
"groupType":"chaddt",
"productCategeory":"bdfjgh",
"members":[
{
"memberId":"0031ea31-a71c-49f8ddbff6-8adaa310db02",
"memberName":"ddddsnta",
"contactId":"5a303564dd-2349-4cca-a190-f36f28ff54cb",
"contactName":"dssnta",
"role":"member"
}
],
}
]
}
This is my json.I am having some difficulty in parsing this.I am trying this solution.please suggest some ideas how to parse this type of json.Thanks for your answer
JSONArray jsonArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < jsonArray.length(); i++) {
groupid = jsonArray.getJSONObject(i).getString("groupId");
String name = jsonArray.getJSONObject(i).getString("name");
String description =jsonArray.getJSONObject(i).getString("description");
String membersCount = jsonArray.getJSONObject(i).getString("membersCount");
String intrested = jsonArray.getJSONObject(i).getString("productCategeory");
JSONArray memberJsonArray = jsonArray.getJSONObject(i).getJSONArray("members");
for (int j = 0; j < memberJsonArray.length(); j++) {
String memberNamename = memberJsonArray.getJSONObject(j).getString("contactName");
String contactId = memberJsonArray.getJSONObject(j).getString("contactId");
String role = memberJsonArray.getJSONObject(j).getString("role");
GroupsDto groupDtoData = new GroupsDto();
groupDtoData.setGroupName(name);
groupDtoData.setGroupServerId(groupid);
System.out.println("groupid"+groupid);
groupDtoData.setGroupDescription(description);
groupDtoData.setProductCategory(intrested);
System.out.println("descr"+intrested);
groupDtoData.setGetmemberCount(membersCount);
groupDtoData.setGroupmembername(memberNamename);
System.out.println("membernames"+memberNamename);
groupDto.add(groupDtoData);
db.addGroups(groupDtoData);
}
This is my json.I am having some difficulty in parsing this.I am trying this solution.please suggest some ideas how to parse this type of json.Thanks for your answer
Your JSON response does not have any array name.
Instead of this :
JSONArray jsonArray = jsonObject.getJSONArray("groups");
Use This:
JSONArray jsonArray = jsonObject.getJSONArray(yourResponseStringHere);
It just needed to use Gson library and create corresponding class with your json file.
Gson : https://github.com/google/gson
Check this answer .It may help you fixing this.
JsonArray jarray=response.getJsonArray("groups");
for(int i=0;i<jarray.length();i++)
{
JsonObject jobj=jarray.getJsonObject(i);
String groupId=jobj.optString("groupId");
//do like this for all
//to get members
JsonArray jarray2=jobj.getJsonArray("members");
for(int j=0;j<jarray2.length();j++)
{
JsonObject jobj2=jarray2.getJsonObject(j);
String memberId=jobj2.optString("memberId");
//do this for all
}
}

How to get values from key/values string in android?

After parsing JSON:
JSONArray jsonArray = new JSONArray(ResponseString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentObject = jsonArray.getJSONObject(i);
String local_parameter = currentObject.getString("LOCAL_PARAMETER");
}
I'm getting next string:
{"Cost": 200,
"Space": 33,
"Accommodation": 1,
"AirConditioning": 1,
"Apartment": 1,
"Campfire": 1,
"Disability": 1,
"Grill": 1,
"Kitchen": 1,
"Monument": 1,
"Parking": 1,
"Scene": 1,
"Wifi": 1,
"ClosedArea": 1 }
How to get ArrayList with key/values?
GOT SOLUTION:
Just get currentObject as JSONObject and then get a string of value what you need:
String cost = currentObject.getJSONObject("LOCAL_PARAMETER")
.getString("Cost").toString();
Just parse the JSON object one more time for the value you need.
JSONArray jsonArray = new JSONArray(ResponseString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentObject = jsonArray.getJSONObject(i);
String local_parameter = currentObject.getString("LOCAL_PARAMETER");
String tmp = local_parameter.get("Cost").toString(); // this gets the value of Cost
}
If you REALLY want to get an ArrayList containing your values, you can do it like this, even if I don't think this way to use JSONObjects is the best one :
final ArrayList<Pair<String, Integer>> values = new ArrayList<Pair<String,Integer>>();
final JSONObject localParams = new JSONObject(local_parameter);
final Iterator<String> iterator = localParams.keys();
while (iterator.hasNext())
{
final String key = iterator.next();
values.add(new Pair<String, Integer>(key, localParams.optInt(key)));
}
But I REALLY don't think this is the best way to handle JSONObjects...
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

How to fetch Data From JSON

I have following data from JSON
{
"MenuName": "starter dish",
"SubMenu": [
"pizza dish1",
"pizza dish2"
],
"Price": [
"100",
"110"
]
},
From here i can easily fetch data from "Menuname" key as starter dish but when I fetch data from "Submenu" I get whole string as ["pizza dish1", "pizza dish2"].
Please suggest me way to differentiate both pizza dish1 and pizza dish2
Submenu and Price is not String it is JSONArray so you will need to use for-loop to get all values from Submenu JSONArray as:
JSONArray jsonsubmenu=yourjsonobject.getJSONArray("Submenu");
for(int i=0;i < jsonsubmenu.length();i++){
// get all values from jsonsubmenu JSONArray..
String str_value=jsonsubmenu.optString(i);
....
}
try this
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getInt("SubMenu");
}
you can use this link for creating POGO class for your response. It will automatically generate class for your response.
Use google GSON library to parse your response.
or you can simply create a JSON Array or Objects to parse it. in your case it is JSON Object or JSON arrays.
Hi There in that senarerio you have to use
JSONArray _submenu = object.getJSONArray("SubMenu");
for (int i = 0; i < _submenu.length(); i++) {
String text = _submenu.getString(i);
}
JSONArray _price = object.getJSONArray("Price");
for (int i = 0; i < _price.length(); i++) {
String text = _price.getString(i);
}
You can retrieve array values and store it in string[] and use them as per your need. i.e., as follows..
try {
JSONObject jObject = new JSONObject(jsonString);
JSONArray jSubmenu = jObject.getJSONArray("SubMenu");
subMenu = new String[jSubmenu.length()];
for (int i = 0; i < subMenu.length; i++) {
subMenu[i] = jSubmenu.getString(i);
}
JSONArray jPrice = jObject.getJSONArray("Price");
price = new String[jPrice.length()];
for (int i = 0; i < price.length; i++) {
price[i] = jPrice.getString(i);
}
} catch (Exception e) {
// TODO: handle exception
}
Just to throw in a quickie - read up on, and use GSON.
For simple small jobs I find it is the best. Not the fastest running for complex, or long structures, but really quick on the dev side.
Here's the link: google-gson

get the index with value using arrayobject and store in array list [duplicate]

This question already has answers here:
get the array index with value using arrayobject and store in array list
(2 answers)
Closed 10 years ago.
[ {
"question_id": 13,
"creation_date": 10,
"name": " certain degrees",
"tags": [
"android",
"sensor"
],
.....
...}
]
Here is the api I want to get the tags array ,the tag array contains only index and value,i want to get the array using array object and finally store in array list, i have tried but fail to get the error has been occured.
02-20 15:45:37.323: I/System.out(1165): org.json.JSONException: Value android at 0 of type java.lang.String cannot be converted to JSONObject
could anybody help me to solve this problem.
tagarray = questionobj.getJSONArray("tags");
for(int j=0;j<tagarray.length();j++){
//tagobject = tagarray.getJSONObject(j);//..if i comment this line the full array list is displaying but i need for each question allocated tags to display..am i clear..
//if(tagobject!=null){
tagname.add(tagarray.getString(j));
///tagname.add(0, null);
//}
}
your json format is not correct
try like that;
{"question":
{"question_id": "13",
"name": "certain degrees",
"tags": [{"android":"N", "sensor":"Y"}]
}}
You can use http://jsonviewer.stack.hu/, to be sure correction of your json data
I sugest you try this code,
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String text = "[ { \"question_id\": 13, \"creation_date\": 10, \"name\": \"certain degrees\", \"tags\": [ \"android\", \"sensor\" ] } ]";
System.out.println(text);
JSONArray jsonArray = new JSONArray(text);
JSONObject jsonObjetc = jsonArray.getJSONObject(0);
JSONArray tagarray = jsonObjetc.getJSONArray("tags");
System.out.println(tagarray);
for(int j=0;j<tagarray.length();j++){
System.out.println(tagarray.getString(j));
}
}
}
Good luck, Aron
Try this,
ArrayList<String> list = new ArrayList<String>();
String text = "[ { \"question_id\": 13, \"creation_date\": 10, \"name\": \"certain degrees\", \"tags\": [ \"android\", \"sensor\" ] } ]";
try {
JSONArray jarray = new JSONArray(text);
for (int i = 0; i < jarray.length(); i++) {
JSONArray j_array = jarray.getJSONObject(i)
.getJSONArray("tags");
for (int j = 0; j < j_array.length(); j++) {
String str = j_array.getString(j);
list.add(str);
}
}
} catch (Exception e) {
}
Try This
tagarray = questionobj.getJSONArray("tags");
for(int j=0;j<tagarray.length();j++)
{
tagname.add(tagarray.getJSONObject(j).getString("android"));
}

Categories

Resources