简体   繁体   中英

json android: parsing json

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!

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");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM