JSON Array Problem
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","ch开发者_StackOverflow社区annels":[{"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.
精彩评论