[英]How parse json object and json array together
i have two situation of Json output . 我有两种情况的Json输出。 one is data that found and i have a json array and a json object like this: 一个是找到的数据,我有一个json数组和一个json对象,如下所示:
{"data":"yes"}[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]
other situation is that data not found : 其他情况是找不到数据:
{"data":"no"}
just one json object. 只是一个json对象。
how parse this data in android client for support two situtaion? 如何在Android客户端中解析此数据以支持两个情景?
First, you should validate your json in http://jsonlint.com/ if you test it you will look that is a wrong json. 首先,您应该在http://jsonlint.com/中验证您的json(如果进行测试),那么您会发现这是错误的json。 So, for make it right, in your server your response should look something like this: 因此,为正确起见,在您的服务器中,您的响应应如下所示:
{"data":"yes","response":[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}
And in that case, in android 在这种情况下,在android中
JSONObject jsonObj = new JSONObject(response);
if (jsonObj.getString("data").compareTo("yes") == 0) {
JSONArray jsonArray = jsonObj.getJSONArray("response");
//To-Do another code
}
and that's all 就这样
Here is a possible case: (you need to fix your json format) 这是一种可能的情况:(您需要修复json格式)
Success - 成功-
string resultJSON =
{"success":true,
"data":[
{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},
{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}
Failed - 失败-
string resultJSON =
{"success":false}
Then 然后
JSONObject jsonRoot = new JSONObject(resultJSON);
bool isSuccess = jsonRoot.getBoolean("success");
if (isSuccess) {
// do the array parser
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonObj = jsonData.getJSONObject(i);
String id = jsonObj.getString("id"); // get the value of id
String desc = jsonObj.getString("desc"); // and so on...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.