JSONObject get data - android

I want to get some json data for my android app from a website that shows it like this:
[ {"id":"33333", "title":"My title" },
{"id":"33344", "title":"My title 2" },
...
]
I have seen some tutorials but i dont realy understand how you can get aal the info in { }.
I have something like this:
for (int i = 0; i < jsonObj.length(); i++) {
String id = jsonObj.getJSONObject("part").getString("id");
}
But it does not work.
What am i doing wrong?

For you specific array there, you need something like this:
JSONArray jsonArray = new JSONArray(your_returned_json_string);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
if (!jsonObj.isNull("id")) {
// do something with id
}
if (!jsonObj.isNull("title")) {
// do something with title
}
}

Pretty simple.
Consider the following is your JSON Array named jsonArray
[
{"id":"33333", "title":"My title" },
{"id":"33344", "title":"My title 2" },
.....
]
You have JSON objects inside this array all of which have a similar format. Hence you need to extract them one by one. This is where the for loop comes into play.
for(int i=0 ; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i); //Get each JSONObject
//Now jsonObject will contain 'i'th jsonObject
//Extracting data from each object will be something like
int id = jsonObject.getInt("id"); //3333
String title = jsonObject.getString("title"); //My title
}

Related

How to read this JSON

String json =
[
{"a":{"aa":"string","ab":"string"} },
{"b":{"ba":"string","bb":"string"} }
]
I am trying to parse this data using JsonObject.
When i use this code :
JSONStringer Js= new JSONStringer(json);
Log.d("json", ""+Js);
it gives me this : (the first line of json but i want all data)
{"a":{"aa":"string","ab":"string"} }
How can I read this with Android ?
It is a JsonArray not a simple JsonObject
try this:
JSONArray a = new JSONArray(json);
for (int i = 0; i < a.length(); i++) {
JSONObject row = a.getJSONObject(i);
Log.d("json", ""+row);
}
Actually, this JSON is kind of weird, as it wraps the array objects into one additional object each ("a" and "b"), which will make it hard to parse. It should look like this:
String json = [ {"name":"a","aa":"string","ab":"string"},
{"name":"b","ba":"string","bb":"string"} ]
And then you would parse it like this:
JSONArray root = new JSONArray(jsonString); //this is the above string
for(int i = 0; i < root.length(); i++){
JSONObject current = root.getJSONObject(i);
//Do the parsing here
}

How to parse Multiple JSON Objects and arrays from a url in android? i am using a example i want it in that example,

I want below process on with out editing on server side
I followed this example
but over there he is calling data with one json object from a url
called "worldpopulation",..
but i have a Json data which is having lot of Json objects and arrays,.. like below code
{ "getting data":"ok"
"Todays":population
{"results"{[
"worldpopulation":
[
{
"rank":1,"country":"China",
"population":"1,354,040,000",
"flag":["http://www.androidbegin.com/tutorial/flag/china.png"]
},
{
"population":{
[
"countrypulation" {
"rank":2,"country":"India",
"population":"1,210,193,422",
"flag":["http://www.androidbegin.com/tutorial/flag/india.png"]
},
like that i have a lot of data i want this data in that above example. Without changing any thing on server side,.. or Restful service,..
thank you
response
JSONObject JObject = new JSONObject(response);
String getting_data = JObject.getstring("getting data");
String Todays= JObject.getstring("Todays");
JsonArray results =JObject.getjsonarray("results");
for(int i = 0 ; i < results.length(); i++){
JsonObject resultsobject =results.getjsonobject(i);
JsonArray worldpopulation
=resultsobject.getjsonarray("worldpopulation");
for(int j = 0 ; j < worldpopulation.length(); j++){
JsonObject worldpopulationobject =worldpopulation.getjsonobject(j);
JsonObject emptyobject =worldpopulationobject.getjsonobject("");
String rank=emptyobject .getstring("rank");
String population=emptyobject .getstring("population");
JsonArray flagarray =countrypulation.getjsonarray(flag);
for(int n = 0 ; n < flagarray.length(); n++){
JsonObject flagarrayobject =flag1array.getjsonobject(n);
String flag=flag1arrayobject .getstring("flag");
}
JsonObject populationobject
=worldpopulationobject.getjsonobject("population");
JsonArray emptyarray =JObject.getjsonarray("");
for(int k = 0 ; k < emptyarray.length(); k++){
JsonObject emptyarrayobject =emptyarray.getjsonobject(k);
JsonObject
countrypulation=emptyarrayobject.getjsonobject("countrypulation");
String rank1=countrypulation .getstring("rank");
String country=countrypulation .getstring("country");
String population1=countrypulation .getstring("population");
JsonArray flag1array =countrypulation.getjsonarray(flag);
for(int m = 0 ; m < flag1array.length(); m++){
JsonObject flag1arrayobject =flag1array.getjsonobject(m);
String flag1=flag1arrayobject .getstring("flag");
}
}
}
}
You parse
{
...
}
as JSONObject and
[
...
]
as JSONArray. JSONArray contains your objects. From the JSONObject you can retrieve the property values.
JSONArray response = new JSONArray('your json string');
for (int i = 0; i < response.length(); i++) {
response.getJSONObject(i).getString("property"));
}
BTW your json is invalid, event if you close the missing brackets. Check it here http://jsonlint.com/

Json parse array with multiple string

i have this input:
[
"1",
"2",
"3",
"5",
"6",
"9",
"10"
]
Could anyone tell me how to parse this kind of json file, that I get from the web? It doesn't have any key for the attribute or something like that.
Try this..
JSONArray array = new JSONArray(response); // get the response as JSONArray
for(int i=0; i < array.length(); i++)
{
Log.v("ALL--", array.getString(i)); // get the values as string using for loop
}
With org.json package, like this (assuming it is in a string):
JSONArray myJSONArray = new JSONArray(inputString);
You can then get the individual elements using:
myJSONArray.getString(i);
You are having JSONArray as your response string so you need to create JSONArray for that
JSONArray jsonArray = new JSONArray(responseString);
Now, you can retrieve the values by their index positions.like,
for(int i = 0; i < jsonArray.length(); i++){
String value = jsonArray.getString(i);
}
Complete code to parse this JSON is,
JSONArray jsonArray = new JSONArray(responseString);
for(int i = 0; i < jsonArray.length(); i++){
String value = jsonArray.getString(i);
}

How to call the JSON object in Android

I am new to the android development. i am having the following android code to call the json
try {
JSONObject jsonObject = new JSONObject(result);
//JSONObject object = jsonObject.getJSONObject("CUSTOMER_ID");
JSONArray jArray = new JSONArray(CUSTOMER_ID);
returnUsername1 = jArray.getInt("CUSTOMER_ID");
Toast.makeText(getApplicationContext(), ""+returnUsername1,Toast.LENGTH_LONG).show();
for (int i = 0; i < jArray.length(); i++) {
}
My JSON format is like [[{"0":"1","CUSTOMER_ID":"1"}]].
i refer some json format it should like [{"0":"1","sno":"1"}] i can understand this.But mine is different from this.
how can i call the customer_id using the above code.anyone can suggest a solution.
What you have is a Json Array
JSONArray jsonarray = new JSONArray(result); // result is a Array
[ represents json array node
{ represents json object node
Your Json. Do you need a Json array twice?
[ // array
[ //array
{ // object
"0": "1",
"CUSTOMER_ID": "1"
}
]
]
Parsing
JSONArray jsonArray = new JSONArray(result);
JSONArray ja= (JSONArray) jsonArray.get(0);
JSONObject jb = (JSONObject) ja.get(0);
String firstvalue = jb.getString("0");
String secondvalue = jb.getString("CUSTOMER_ID");
Log.i("first value is",firstvalue);
Log.i("second value is",secondvalue);
LogCat
07-22 14:37:02.990: I/first value is(6041): 1
07-22 14:37:03.048: I/second value is(6041): 1
Generally, to get a JSONObject from a JSONArray:
JSONObject jsonObject = jsonArray.getJSONObject(0); //0 -> first object
And then
int userID = jsonObject.getInt("CUSTOMER_ID");
CUSTOMER_ID is not considered a JSONObject in this case. If jsonObject is what you think it is, then you should be able to access it with jsonObject.getString("CUSTOMER_ID")
if you have any problems regarding to your JSON format first validate it through this site
http://jsonlint.com/
then for parsing
JSONObject jsonObject = new JSONObject(result);
// since your value for CUSTOMER_ID in your json text is string then you should get it as
// string and then convert to an int
returnUsername1 = Integer.parseInt(jsonObject.getString("CUSTOMER_ID"));
Try this
JSONObject jsonObject = new JSONObject(result);
JSONArray jArray =json.getJSONArray("enterjsonarraynamehere");
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String cust= oneObject.getString("CUSTOMER_ID");
} catch (JSONException e) {
// Oops something went wrong
}
}
Im assuming your json is something like this
<somecode>
{
"enterjsonarraynamehere": [
{ "0":"1",
"CUSTOMER_ID":"1"
},
{ "0":"2",
"CUSTOMER_ID":"2"
}
],
"count": 2
}
<somecode>

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

Categories

Resources