On a web service I a, getting a json as follows in android application. I would likes to make a loop table view in android with lists object. Please help me how to make the loop. I successed by making table row. Still I am confusing with how to pass data
My JSON
{
"id":4,
"access_token":"tge4sn1vdgbjcvvf",
"session":1,
"lists":[
{
"name":"name 1"
},
{
"name":"name 2"
},
{
"name":"name 3"
},
{
"name":"name 4"
},
{
"name":"name 4"
}
]
}
My Code
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
JSONObject jsono = stringToJsonobj(a);
String passedStringValue = jsono.getString("session");
if(passedStringValue.equals("1")){
// I want the loop here
// Tried this - myListsAll=jsono.getJSONObject("lists");
}
Any one please help me how to parse this data
Thanks in advance
lists is JSONArray instead of JSONObject.currently you are trying to get it as an JSONObject.you can iterate through lists JSONArray as:
if(passedStringValue.equals("1")){
JSONArray myListsAll=jsono.getJSONArray("lists");
for(int i=0;i<myListsAll.length();i++){
JSONObject jsonobject=myListsAll.getJSONObject(i);
// get name from jsonobject object
String str_name=jsonobject.optString("name");
}
}
Related
I have already checked other posts of Stack Overflow regarding Json data parsing but did not find the solution to parse inner Json int objects.
I am getting the following response from a web service.
{
"counter":[
{
"1":[
{
"message":"28",
"events":0,
"shared_files":"8"
}
],
"2":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
.....
"n":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
}
]
}
Where "1", "2" and "n" are ids and json object size changes according to the data. I am able to parse the above response till JsonObect using following code:
JsonArray jsonArray = GetJson_.getArray(response, "counter");
if (jsonArray != null) {
JsonObject object = jsonArray.get(0).getAsJsonObject();
}
and my jsonObject now looks like
{
"1":[
{
"message":"28",
"events":0,
"shared_files":"8"
}
],
"2":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
.....
"n":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
}
But I am stuck at how to parse the JsonObject which is dynamic.
Please help.Thanks in advance.
hey you may use HashMap<> for parse dynamic key response for this check this link, other way you may use Iterator which i done below :
JSONObject jsonObject= m_jArry.getJSONObject(0);
Log.e("ad","--------"+jsonObject.toString());
Iterator keys = jsonObject.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = jsonObject.getJSONObject(currentDynamicKey);
// do something here with the value...
}
Hope this will helpful to you.
i have a JSON like below.
this is sample json.. i have my json structure like this. if this json has any error please ignore that.
[
[
"{"category_id":1,"category_name":"1Appetizers","image_id":0}",
"{"category_id":13,"category_name":"Buffet","image_id":0}"
],
[
"{"subcategory_id":1,"category_id":12,"subcategory_name":"Beer","image_id":0}",
"{"subcategory_id":2,"category_id":12,"subcategory_name":"Wine","image_id":0}"
],
[
"{"menucategory_id":1,"menucategory_id":12,"menucategory_name":"dosa","image_id":0}",
"{"menucategory_id":2,"menucategory_id":12,"menucategory_name":"idly","image_id":0}"
]
]
how do i parse this JSON in android. i want to show category_name in one page and other details in some other page. there is no name for object.
Like the other commenters have mentioned this is not real JSON.
But here is an attempt to answer your question anyway.
I would create objects that represents the data you want to serialize and deserialize to and form JSON. It looks like you would have objects Category, Subcategory, and MenuCategory. Then you would probably have another object that holds lists of those three objects.
Then I would use GSON to serialize and deserialize your object. Let it do the heavy lifting for you.
try the following code. it might help you
// say you have your json in a String named jsonString
try
{
JSONArray array = new JSONArray(jsonString);
JSONArray firstJsonArray = array.getJSONArray(0);
JSONArray secondJsonArray = array.getJSONArray(1);
JSONArray thirdJsonArray = array.getJSONArray(2);
for (int i = 0; i < 2; i++)
{
JSONObject firstJsonObject = firstJsonArray.getJSONObject(i);
JSONObject secondJsonObject = secondJsonArray.getJSONObject(i);
JSONObject thirdJsonObject = thirdJsonArray.getJSONObject(i);
String categoryName = firstJsonObject.getString("category_name");
String subcategoryName = secondJsonObject.getString("subcategory_name");
String menucategoryName = thirdJsonObject.getString("menucategory_name");
// Now here you can use these values to do anything
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
I'm currently working on an Android application that gets a JSON response from a website called CloudMine. Their responses are typically in this format:
{
"success": {
"key1": { "field": "value1" },
"key2": { "field1": "value1", "field2": "value2" }
},
"errors": {
"key3": { "code": 404, "message": "Not Found" }
}
}
I currently want to loop through all the objects in the "success" object so I can access the different fields in each object. However, I've only been taught how to use the JsonParser from the gson API. The closest I got was using the names() method on the success object but Eclipse yelled at me because the method is undefined for this type.
I appreciate all the help that anyone can give me.
Thanks!
This worked for me:
JsonObject myJsonObject = new Gson().fromJson(myJsonString, JsonObject.class);
for (Map.Entry<String, JsonElement> entry : myJsonObject.entrySet()) {
JsonObject entryObj = entry.getValue().getAsJsonObject();
}
Based on the accepted answer to this question, although I've altered it for my use case:
Iterate over JsonObject properties
Here's a very simple code that would iterate over objects in 'success':
JSONObject json = new JSONObject(responseString);
JSONObject success = json.getJSONObject("success");
JSONObject one;
for(Iterator it=success.keys(); it.hasNext(); ) {
one = success.getJSONObject((String)it.next());
//deal with the next object inside your 'success'
}
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 {
...
}
hi does anyone know how to create a Array that contains objects that in each objects contain several objects? i just can't seem to get my head round it
the structure should look like this
Array{[object]{subobject,subobject}
[object]{subobject,subobject}
}
heres what i have so far
JSONObject obj = new JSONObject(json2);
JSONObject objData = obj.getJSONObject("data");
fixturesArray = objData.getJSONArray("fixtures");
JSONArray FixArray = new JSONArray();
for(int t = 0; t < fixturesArray.length(); t++){
JSONObject fixObj = fixturesArray.getJSONObject(t);
String Matchdate = fixObj.getString("matchdate");
JSONObject DateObj = DateObj.put(Matchdate, DateObj);
heres my JSON essentially what i have if is a feed of fixtures i need to order them in to arrays of dates
{
"code":200,
"error":null,
"data":{
"fixtures":[
{
"kickoff":"15:00:00",
"matchdate":"2012-07-28",
"homescore":null,
"awayscore":null,
"attendance":null,
"homepens":null,
"awaypens":null,
"division_id":"5059",
"division":"Testing 1",
"comp":"LGE",
"location":null,
"fixture_note":null,
"hometeam_id":"64930",
"hometeam":"Team 1",
"awayteam_id":"64931",
"awayteam":"Team 2"
}, {
"kickoff":"15:00:00",
"matchdate":"2012-07-28",
"homescore":null,
"awayscore":null,
"attendance":null,
"homepens":null,
"awaypens":null,
"division_id":"5059",
"division":"Testing 1",
"comp":"LGE",
"location":null,
"fixture_note":null,
"hometeam_id":"64930",
"hometeam":"Team 1",
"awayteam_id":"64931",
"awayteam":"Team 2"
}
]
}
}
Do you mean that?:
JSONObject obj = new JSONObject();
obj.put("x", "1");
JSONObject parent_object = new JSONObject();
parent_object.put("child", obj);
JSONArray array = new JSONArray(parent_object.toString());
JSON String
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea"}
]
}
Here below I am fetching country details
JSONObject json = new JSONObject(jsonstring);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
What I would suggest to do is to use JackSON JSON Parser library http://jackson.codehaus.org/ Then you can create a Class with the same fields as the JSON son the mapping from JSON To class will be direct.
So once you have all the items from JSON into a List of class you can order by dates or manipulate data as you want. Imagine that src is a String containing the JSON text. With JackSON lib you just need to do this.
ObjectMapper mapper = new ObjectMapper();
List<Fixture> result = mapper.readValue(src, new TypeReference<List<Fixture>>() { });
Here are two pieces of JSON which fit your description which is "Array that contains objects that in each objects contain several objects". The first method uses Arrays inside Objects. The other one uses Objects in Objects.
Method 1
[ { "name" : "first object in array" , "inner array" : [ { <object> } , { <object> } ] }
, { "name" : "second object in array" , "inner array" : [ { <object> } , { <object> } ] } ]
To parse the above you need two nested for loops (or something recursive).
Method 2
[ { "name" : "first object in array" , "first inner object" : { <object> } , "second inner object" : { <object> } } , <etc.> ] } ]
The second method can be parsed with a single for loop because you know in advance the number of inner objects to expect.