JSON Array Problem - java

Hy!
I have a JSON Array with the tv channels and the lenght of the array is three, but after transmitting into a treemap the Value is only one.
Please Help
Code:
try
{
JSONObject menuobj = this.getJSONObject("responseData");
Log.e("XXX", menuobj.toString());
JSONArray array = menuobj.getJSONArray("countries");
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
for (int i = 0; i < array.length(); i++)
{
JSONObject obj = new JSONObject();
obj = array.getJSONObject(i);
if (obj.getString("name").equals(country))
{
Log.e("XXX2", obj.toString());
JSONArray arr = obj.getJSONArray("channels");
Log.e("XXX3", String.valueOf(arr.length()));
for (int j = 0; j < arr.length(); j++)
{
JSONObject obj2 = new JSONObject();
obj2 = arr.getJSONObject(i);
map.put(obj2.getString("name"), obj2.getInt("id"));
}
Log.e("XXX4", String.valueOf(map.size()));
return map;
}
}
LogCat:
02-01 18:24:20.277: ERROR/XXX(3784): {"countries":[{"id":"1","channels":[{"id":"3","name":"ARD"},{"id":"1","name":"ORF 1"},{"id":"2","name":"ORF 2"}],"name":"Ã?sterreich"},{"id":"2","channels":[{"id":"3","name":"ARD"}],"name":"Deutschland"}]}
02-01 18:24:20.288: ERROR/XXX2(3784): {"id":"1","channels":[{"id":"3","name":"ARD"},{"id":"1","name":"ORF 1"},{"id":"2","name":"ORF 2"}],"name":"Ã?sterreich"}
02-01 18:24:20.297: ERROR/XXX3(3784): 3
02-01 18:24:20.307: ERROR/XXX4(3784): 1

I believe :
obj2 = arr.getJSONObject(i);
should be
obj2 = arr.getJSONObject(j);
So you are putting three times the same object pair of key/value to the map.

You need to use JSONArray without JSONObject:
JSONArray resultJson = new JSONArray(responseDataString);

You're missing an important logging detail, call it XXX3.5. It's almost certainly the case that the map contains one element because each call to map.put() is passing in a key that is considered equal to the key already inside the map.
Now I'd expect these keys to be the String names of the channels, which are distinct, so clearly this expectation isn't holding. Adding a log message of obj2.getString("name") (or alternatively setting a breakpoint there), will let you see what the map keys actually are, and why subsequent calls are overwriting the existing mapping. Outputting the actual class of the object would be useful too, in order to distinguish between an actual String and some class that merely contains a String.
If the elements look sensible, the problem could be a loose definition of equals() on the class in question, which equates elements that ought to seem distinct. In any case, better logging will show why
arr.getJSONObject(0).getString("name").equals(arr.getJSONObject(1).getString("name")
returns true when you expect this to return false.

Related

JSON array parsing with Java [duplicate]

I am building an android app that needs to download and synchronise with an online database, I am sending my query from the app to a php page which returns the relevant rows from a database in JSON format.
can someone please tell me the best way to iterate through a JSON array?
I receive an array of objects:
[{json object},{json object},{json object}]
What is the simplest piece of code I could use to access the JSONObjects in the array?
EDIT: now that I think of it the method I used to iterate the loop was:
for (String row: json){
id = row.getInt("id");
name = row.getString("name");
password = row.getString("password");
}
So I guess I had was somehow able to turn the returned Json into and iterable array. Any Ideas how I could achieve this?
I apologise for my vaguness but I had this working from an example I found on the web and have since been unable to find it.
I think this code is short and clear:
int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
Is that what you were looking for?
I have done it two different ways,
1.) make a Map
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i=0; i<settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
2.) make a JSONArray of names
JSONArray names = json.names();
JSONArray values = json.toJSONArray(names);
for(int i=0; i<values.length(); i++){
if (names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if (names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if (names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if (names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Unfortunately , JSONArray doesn't support foreach statements, like:
for(JSONObject someObj : someJsonArray) {
// do something about someObj
....
....
}
When I tried #vipw's suggestion, I was faced with this exception:
The method getJSONObject(int) is undefined for the type JSONArray
This worked for me instead:
int myJsonArraySize = myJsonArray.size();
for (int i = 0; i < myJsonArraySize; i++) {
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
// Do whatever you have to do to myJsonObject...
}
If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the Iterable interface and add the following method to the class:
#Override
public Iterator iterator() {
return this.myArrayList.iterator();
}
This will make all instances of JSONArray iterable, meaning that the for (Object foo : bar) syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.
On Arrays, look for:
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
You are using the same Cast object for every entry.
On each iteration you just changed the same object instead creating a new one.
This code should fix it:
JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();
for (int i=0; i < jCastArr.length(); i++) {
Cast person = new Cast(); // create a new object here
JSONObject jpersonObj = jCastArr.getJSONObject(i);
person.castId = (String) jpersonObj.getString("id");
person.castFullName = (String) jpersonObj.getString("name");
castList.add(person);
}
details.castList = castList;
While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for null objects; for example, you may get "null" instead of a null string.
A check may look like:
s[i] = array.isNull(i) ? null : array.getString(i);

How to loop through json arrays nested inside json objects

I have this json text which has some symptoms associated with head diseases:
{
"Head": {
"Agitation": {
"conditions": "Generalized anxiety disorder,Medication reaction or side-effect"
},
"Anxiety": {
"conditions": "Generalized anxiety disorder,Depression (Adult)"
},
"Apathy": {
"conditions": "Depression (Adult),Medication reaction or side-effect,Dementia in head injury"
}
}
}
What I want is to access and display every symptom in this Head block using a for loop, and then access each symptom's conditions and store them separately as arrays.
This java code works but it's functionality is limited:
JSONObject jsonObject = (JSONObject) object;
JSONObject bodyPart = (JSONObject) jsonObject.get("Head");
JSONObject symptoms = (JSONObject) name.get("Agitation");
String res = (String) symptoms.get("conditions");
String[] tokens = res.split(",");
for (int i = 0; i < tokens.length; i++){
System.out.println(tokens[i]);}
Instead of displaying just the conditions of Agitation, how can I display every condition associated with every symptom without having to pass their String values manually into the get methods?
I don't know if I should use JSONArray for "Head" instead of JSONObject to access the symptoms.
Assuming this is the org.json package, you can use JSONObject's keys() method to get an iterator over the object's keys.
Iterator bodyParts = jsonObject.keys();
while (bodyParts.hasNext()){
String bodyPart = (String) bodyParts.next();
JSONObject symptomsJson = jsonObject.getJSONObject(bodyPart);
Iterator symptoms = symptomsJson.keys();
// And so on...
}
My friend, if you're using java, use objects, no plain text, my recommendation is to use Json.simple,
That way you can have List of objects and use the properties you want, take a look on the link examples.

how to iterate the json objects in the jsonarray [duplicate]

I am building an android app that needs to download and synchronise with an online database, I am sending my query from the app to a php page which returns the relevant rows from a database in JSON format.
can someone please tell me the best way to iterate through a JSON array?
I receive an array of objects:
[{json object},{json object},{json object}]
What is the simplest piece of code I could use to access the JSONObjects in the array?
EDIT: now that I think of it the method I used to iterate the loop was:
for (String row: json){
id = row.getInt("id");
name = row.getString("name");
password = row.getString("password");
}
So I guess I had was somehow able to turn the returned Json into and iterable array. Any Ideas how I could achieve this?
I apologise for my vaguness but I had this working from an example I found on the web and have since been unable to find it.
I think this code is short and clear:
int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
Is that what you were looking for?
I have done it two different ways,
1.) make a Map
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i=0; i<settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
2.) make a JSONArray of names
JSONArray names = json.names();
JSONArray values = json.toJSONArray(names);
for(int i=0; i<values.length(); i++){
if (names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if (names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if (names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if (names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Unfortunately , JSONArray doesn't support foreach statements, like:
for(JSONObject someObj : someJsonArray) {
// do something about someObj
....
....
}
When I tried #vipw's suggestion, I was faced with this exception:
The method getJSONObject(int) is undefined for the type JSONArray
This worked for me instead:
int myJsonArraySize = myJsonArray.size();
for (int i = 0; i < myJsonArraySize; i++) {
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
// Do whatever you have to do to myJsonObject...
}
If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the Iterable interface and add the following method to the class:
#Override
public Iterator iterator() {
return this.myArrayList.iterator();
}
This will make all instances of JSONArray iterable, meaning that the for (Object foo : bar) syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.
On Arrays, look for:
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
You are using the same Cast object for every entry.
On each iteration you just changed the same object instead creating a new one.
This code should fix it:
JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();
for (int i=0; i < jCastArr.length(); i++) {
Cast person = new Cast(); // create a new object here
JSONObject jpersonObj = jCastArr.getJSONObject(i);
person.castId = (String) jpersonObj.getString("id");
person.castFullName = (String) jpersonObj.getString("name");
castList.add(person);
}
details.castList = castList;
While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for null objects; for example, you may get "null" instead of a null string.
A check may look like:
s[i] = array.isNull(i) ? null : array.getString(i);

Returning string representation of key value pairs in JSONArray

for (int i = 0; i < jsonArray.length(); i++){
System.out.println(jsonArray.getJSONObject(i));
System.out.println(jsonArray.getJSONObject(i).names());
}
Will print pairs, and then individual objects, such as
{"key1":"a"}
["key1"]
{"key2":"b"}
["key2"]
{"key3":"c"}
["key3"]
{"key4":"d"}
["key4"]
...
{"keyn":"end"}
["keyn"]
I'm wanting the for loop to be able to grab the string interpretation of the key and value for each object separately.
I've been searching through the JSONObject API but I can't seem to find a method in there that would do that. It's easy to grab the name of a value if you know the name of the key:
jsonObject.getString(whenYouKnowTheKeyName));
But when I'm looping through an array I'm assuming I know neither. I'm looking to get
key1
a
key2
b
key3
c
key4
d
...
as the output. I'm attempting to read from an already created JSON object, not create a new one.
Assuming the objects in jsonArray always contain exactly one key, the following should print the key and value in each object as you would like:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Iterator<String> keys = jsonObject.keys();
String key = keys.next();
Object value = jsonObject.get(key);
System.out.println(key);
System.out.println(value);
}
However, you may want to handle all the keys of all the objects by wrapping each key and value in a while (keys.hasNext()) iterator loop:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Object value = jsonObject.get(key);
System.out.println(key);
System.out.println(value);
}
}
With your example, both solutions have the same output, but obviously the latter is more flexible.

How to parse JSON Array and stored in arraylist in java?

I want to parse following JSON array and store in array list.
[{"type":{"Male":"1","Female":"2"}}]
I have tried following code
JSONObject object=getJSONObject(0).getString("type");
Result:
{"Male":"1","Female":"2"}
Here type is the key and others are values.
It comes with comma, quotes.How to store this values are in ArrayList?
Something like the below should do the trick for your JSON. Seeing your JSON I don't see an Array anywhere.
String resultJson; // Assuming this has the JSON given in the question.
JSONObject object = new JSONObject(resultJson);
JSONObject type = object.getJSONObject("type"); //Get the type object.
HashMap<String, Integer> map = new HashMap<String, Integer>(); //Creating the Map
String male = type.getString("male"); //Get the male value
String female = type.getString("female"); //Get the female value
map.put("male", Integer.parseInt(male));
map.put("female", Integer.parseInt(female));
Something like this?
ArrayList<String> list = new ArrayList<String>();
if (jsonArray != null) { //In this case jsonArray is your JSON array
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}

Categories

Resources