json android: parsing json

2019-08-30 05:33发布

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!

2条回答
神经病院院长
2楼-- · 2019-08-30 06:17

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

查看更多
看我几分像从前
3楼-- · 2019-08-30 06:19

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.

查看更多
登录 后发表回答