json android: parsing json

一笑奈何 提交于 2019-12-25 09:45:14

问题


I have a json :

[ {user:"John",s:"Ldh",e:"usa"},{user:"Paul",s:"bukit panjang ",e:"FedExForum - Memphis"},{user:"ross",s:"bukit panjang ",e:"FedExForum - Memphis "}]

I am parsing this with the following code to retrieve all the values of "user" ..

public class ListViewAndroidActivity extends ListActivity {
private String newString, user;
ArrayList<String> results = new ArrayList<String>();
@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
TestServiceActivity test = new TestServiceActivity(); //This returns json from the server
   newString = test.readPooledFeed(); // returned json in string format

   JSONArray rootArray = new JSONArray(newString);
   int len = rootArray.length();
   for(int i = 0; i < len; ++i) {
       JSONObject obj = rootArray.getJSONObject(i);

      user = obj.optString("user");
    results.add(user);
   }
}

This gives me no error.. but nothing is shown on the screen .. kindly help!


回答1:


optString : Get an optional string associated with a key.

I don't see the key u in your JSON object, shouldn't it be user = obj.optString("user");




回答2:


JSON formatting

Your JSON data is not valid, it's valid as javascript, but not as JSON.

All properties should be quoted in JSON:

[
 { "user": "John", "s": "Ldh", "e": "usa"},
 { "user":"Paul", "s":"bukit panjang ", "e": "FedExForum - Memphis" },
 { "user": "ross", "s":"bukit panjang ", "e":"FedExForum - Memphis "}
]

Indentation is not needed, I just did it to make it clearer.

Missing field

Your parser seems to ignore that your input data is invalid. Other problem could be as others mentioned you're requesting the u property at user = obj.optString("u"); which does not exists.



来源:https://stackoverflow.com/questions/8215193/json-android-parsing-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!