Populating Spinner data from json - android

I have some problem... when i try to populating spinner data from json
this, my json data :
parse bank and product work normally
Bank.
Product.
Provider no data
Log.
what should i do to parse provider to android spinner ?

Try this..
provider is inside product array
"product": [ // JSONArray
{ // JSONObject
"id": "1",
"value": "PULSA",
"name": "Pulsa Telpon",
"provider": [ // JSONArray
Code
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONObject product_obj = jsonObj.getJSONArray("product").getJSONObject(0);
JSONArray categories = product_obj
.getJSONArray("provider");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("id"),
catObj.getString("name"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Here you are trying to fetch provider jsonArray from the jsonobject formed using the json response json.
JSONArray categories = jsonObj.getJSONArray("provider");
however the provider jsonArray is not in the base jsonobject, but it is in the product jsonArray. That is why you are not getting any data for provider.
Solution :
first get the product jsonarray from the base jsonobject. Then extract the provider jsonarray for each product in loop.
Algorithm or Flow:
JSONObject jsonObj = new JSONObject(json); // Base json object
JSONArray bankArray = jsonObj.getJSONArray("bank"); // Bank json array
JSONArray productArray = jsonObj.getJSONArray("product"); // Product json array
// no. of items in product
int arrayLength = productArray.length();
for (int i = 0; i < arrayLength; i++) {
// get single product object from array
JSONObject singleProductObject = productArray
.getJSONObject(i);
// Get the provider array for every product
JSONArray providerArray = singleProductObject.getJSONArray("provider");
}
This way you will get the provider data.
Hope it helps you.

What I understand your Json object contains to memeber that is a array bank and product
provider is inner array od product.
I am not sure if you take care of this
try this only for single product
JSONArray categories = jsonObj.getJSONArray("product")[0].getJSONArray("provider");

Related

How to parse JSON using hardocoded values

I am trying to parse json but it gives me exception.
I hardcoded expected json as String like this
String stringJSON="[{\"value1\":\"ABC567123\",\"end_at\":\"08/28/2014 09:10:00\",\"start_at\":\"04/25/2016 09:20:00\"}]";
Valid json is like this
[
{
"value1": "ABC567123",
"end_at": "08/28/2014 09:10:00",
"start_at": "04/25/2016 09:20:00"
}
]
Now I am trying to parse json like below and getting exception.
JSONObject responseObJ;
try {
responseObJ= new JSONObject(stringJSON); //error here
if(responseObJ!=null){
//do something
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Please suggest what to do?
//hard coded it for temporary - json result is expected to exact same
stringJSON is contains JSONArray instead of JSONObject as root element in JSON String.
Either remove [] from start and end of String according to current code or if multiple JSONObject's is available in JSONArray then get JSONArray from stringJSON :
JSONArray responseObJ= new JSONArray(stringJSON);
[ ] they show that it has an array of objects in it so you can retrieve it like this
JSONArray jsonArray= new JSONArray(stringJSON);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jObject.getJSONObject(i);
// here you can get the values of objects stored in the jsonObject
}
In your case you have only one object so you don't have to use loop instead you can get it like this
JSONArray jsonArray= new JSONArray(stringJSON);
JSONObject jsonObject = jObject.getJSONObject(0);
yes as you said its valid json but its JsonArray not JsonObject.
Just remove [] from start and end.
your string should be
String stringJSON="{\"value1\":\"ABC567123\",\"end_at\":\"08/28/2014 09:10:00\",\"start_at\":\"04/25/2016 09:20:00\"}";
or if you want to work with current string then use JsonArray instead of JsonObject
JSONArray responseObJ= new JSONArray(stringJSON);
Can you try Deserialize method of ScriptSerializer class? Like:
var scriptSerializer = new JavaScriptSerializer();
var obj = scriptSerializer.Deserialize<Object>(str);

How to check JSON object and array

I have 2 links; which gives json data. I am trying to get the values from the urls from the same activity in android using asynTask. did the coding till converting the data to string(stored it in jsonStr1). But now comes the problem. Because,among the 2 urls:
one starts with JSON object-
{ "contacts": [ {"id": "c200", "name": "Ravi Tamada" },
{ "id": "c201", "name": "Johnny Depp" }
]
}
another start with JSON array-
[{"appeId":"1","survId":"1"},
{"appeId":"2","survId":"32"}
]
Now how am i going to give a condition for them whether to know its a JSON array or Object? JSON array are object that i know but cant find how to separate them. i have tried the below:
JSONObject jsonObj = new JSONObject(jsonStr1);
if(jsonObj instanceof JSONArray){}
but if condition is showing error- incompatible conditional operand types JSONObject and JSONArray
You can simply use startsWith for String to check where the String starts with { or [
boolean isJsonArray = jsonResponse.startsWith("[");
if(isJsonArray){
// Its a json array
}
else{
// Its a json object
}
You can use JSONTokener class for that, here is a sample code for that.
Object json = new JSONTokener(response).nextValue();
if (json instanceof JSONObject){
JSONObject result = new JSONObject(response);
}
else if (json instanceof JSONArray){
JSONArray resultArray = new JSONArray(response);
}
make jsonobject and call which place u want to calling
jsonobject = JSONfunctions
.getJSONfromURL("http://ampndesigntest.com/androidapi/CURRENTPROJECTDATA/textfiles/hotels");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("flag", jsonobject.getString("flag"));
// map.put("latlongitude", jsonobject.getString("latlongitude"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
You could use the method has(String) to check if the JSONObject contains or not the key contacts.
if(jsonOjbect.has("contacts") {
...
}
else {
...
}

Android JSONObject How get few JSONObject of one

I have JSONObject and I want get 8 object A,B,C...
my json string:
{"Matches":{"A":[{"team1":"Russia","team2":"France","time":"00:00:00","time0_90":"20","score":"0 : 0","stadium":"Maracana","referee":"ref","group":"A"},{"team1":"Portugal","team2":"Honduras","time":"00:00:00","time0_90":"60","score":"0 : 2","stadium":"","referee":"","group":"A"}]},"success":1}{"Matches":{"B":[{"team1":"Brazil","team2":"Spain","time":"00:00:00","time0_90":"3","score":"1 : 0","stadium":"","referee":"","group":"B"}]},"success":1}{"Matches":{"C":[]},"success":0}{"Matches":{"D":[]},"success":0}{"Matches":{"E":[]},"success":0}{"Matches":{"F":[]},"success":0}{"Matches":{"G":[]},"success":0}{"Matches":{"H":[]},"success":0}
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMathes = jsonResponse.optJSONArray("matches");
// ????????
Your response structure is:
JSONObject
key:value
JSONObject (key: "Matches")
JSONArray (key: "A")
JSONObject,
key:value,
key:value,
etc...
JSONObject
To get access to A, follow the steps below:
Create JSONObject from your response:
JSONObject jsonResponseObj = new JSONObject(jsonResponse);
Get JSONObject for the key "Matches"
JSONObject jsonMatches = jsonResponseObj.getJSONObject("Matches");
This object contains a JSONArray for the key "A", so let's get that array:
JSONArray jsonArrayA = jsonMatches.optJSONArray("A");
For your response, you have 2 JSONObjects in this array, so first, let's declare and initialize them:
//two JSONObjects
JSONObject[] jsonObjects = new JSONObject[jsonArrayA.length()];
//go through the array of JSONObjects and fetch them
for (int i=0; i < jsonObjects.length; i++) {
jsonObjects[i] = jsonArrayA.getJSONObject(i);
}
You now have A as JSONArray in jsonArrayA
A contains 2 JSONObjects, and you have them in jsonObjects[0] and josnObjects[1]
If you want to get the contents of those jsonObjects, simply fetch it using the keys, eg.:
String team1Obj1 = jsonObjects[0].getString("team1"); // will contain 'Russia'
String team2Obj2 = jsonObjects[1].getString("team2"); // will contain 'Honduras'
String stadium1 = jsonObjects[0].getString("stadium"); // will contain 'Maracana'
etc.

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>

Simple Json parsing in android

I got the Json response. I am not able to get the values from the string.my string is
Json_response is
{"NameAllList":[{"Current":{"time":"2012-02-21T08:04:21","Name":"abcd"},
"Next":{"Name":"data1","StartTime":"2012-02-21T08:06:21"}},{"Current":{"time":"2012-02-21T08:14:21","Name":"defg"},
"Next":{"Name":"data2","StartTime":"2012-02-21T08:24:21"}},{"Current":{"time":"2012-02-21T08:28:21","Name":"ghij"},
"Next":{"Name":"data3","StartTime":"2012-02-21T08:34:21"}},{"Current":{"time":"2012-02-21T08:40:21","Name":"knmo"},
"Next":{"Name":"data4","StartTime":"2012-02-21T08:48:21"}}]}
and i tried this.
JSONObject jsonObj = new JSONObject(json_response);
JSONObject subObj = jsonObj.getJSONObject("Current");
String name_current =subObj.getString("Name");
but i am not able to get the value of "Name". what mistake i have done. provide the link to do the above parsing.
first of all, your JSON response is having NameAllList as a JSON Array of objects.
So you have to fetch JSON Array first, then you can fetch one-by-one object.
for example:
JSONObject jsonString = (new JSONObject(json_response_string));
JSONArray array = jsonString.getJSONArray("NameAllList");
for(int i=0; i<array.length(); i++)
{
// Retrieve Current object as such
JSONObject objCurrent = array.getJSONObject("Current");
// Retrieve Next object as such
JSONObject objNext = array.getJSONObject("Next");
}
You are not parsing json properly, so you are not able to fetch value of Name. Please note JSON Annotation [] represent JSONArray, and {} respresent JSONObject, so method to get current item's name is:
JSONObject jsonObj = new JSONObject(json_response_string);
JSONArray jsonArr=jsonObj.getJSONArray("NameAllList");
String Hora_name_current="";
for(int i=0;i<jsonArr.length();i++)
{
JSONObject obj=jsonArr.get(i);
try{
JSONObject subObj = obj.getJSONObject("Current");
Hora_name_current =subObj.getString("Name");
break;
}catch(JSONException ex)
{
}
}
looks like you're trying to use JSONObject when you should be using JSONArray for the second request. Try this:
JSONObject jsonString = (new JSONObject(json_response_string));
JSONArray array = jsonString.getJSONArray("NameAllList");
In your JSON return, "NameAllList is actually an array and needs to be handled as such. Once you set it to "array", you can then run a for loop and treat it like any other array in Java.
Let me know if that helps.
David
JSONObject jsonObj = new JSONObject(json_response_string);
JSONArray jsonArray = jsonObj.getJSONArrays("NameAllList");

Categories

Resources