如何循环JSON数据&在JSON文件中解析没有数组

时间:2015-07-28 14:41:30

标签: java android arrays json loops

我试图解析没有数组的JSON数据,此时我的代码循环通过JSONArray并正常工作。

ISSUE / ERROR

我不确定如何在没有数组的情况下使用JSON。当我没有数组长度来处理没有数组的JSON时,我该如何循环。

代码: - 目前适用于带有数组

的JSON数据
JSONArray inbox = null;

List<NameValuePair> params = new ArrayList<NameValuePair>();

 // getting JSON string from URL
  JSONObject json = jsonParser.makeHttpRequest(INBOX_URL, "GET",
                params);

try {

        inbox = json.getJSONArray(TAG_ARRAY);
    inbox.toString();

 // looping through All messages
 for (int i = 0; i < inbox.length(); i++) {
 JSONObject c = inbox.getJSONObject(i);

    // Storing each json item in variable
String id = c.getString(TAG_ID);
String person = c.getString(TAG_PERSON);
….. 
…..
…..
// creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_ID, id);
                map.put(TAG_FROM, person);
….. 
…..
…..

没有阵列的JSON

[
    {
        "id": "1",
        "person": "David",
        "thur": "",
        "grade": "15",
        "round": "",
        "tour": ""
    },
    {
        "id": "T2",
        "person": "Mary",
        "thur": "",
        "grade": "13",
        "round": "",
        "tour": ""
    },


]

带阵列的JSON - 以上代码适用于此

{
    "id": [
        {
            "id": "1",
            "person": "Jason",
            "thur": "F",
            "grade": "17",
            "round": "2"
        },
        {
            "id": "2",
            "person": "Joe",
            "grade": "F",
            "score": "16",
           "round": "3"
        }

]

2 个答案:

答案 0 :(得分:0)

你试过这个吗?

  

JSONObject jsonObject = new JSONObject(); try { JSONArray jsonArray = new JSONArray(jsonObject.toString()); } catch (JSONException e) { e.printStackTrace(); }

但我建议您使用Google Library GSON(https://github.com/google/gson)从其他客户端获取JSON值

答案 1 :(得分:0)

不知道你的解析器方法(makeHttpRequest())是如何工作的 但改变makeHttpRequest()方法的定义..所以它返回jsonarray .. 因为你的json是jsonarray ..它还包含每个索引的jsonobject

JSONArray inbox = null;
List<NameValuePair> params = new ArrayList<NameValuePair>();

// getting JSON string from URL
JSONArray json = jsonParser.makeHttpRequest(INBOX_URL, "GET",params);

try {
    //inbox = json.getJSONArray(TAG_ARRAY);
    //inbox.toString();

    //comment the above 2 line and the rest is same
    // looping through All messages
    for (int i = 0; i < json.length(); i++) {
    JSONObject c = json.getJSONObject(i);

    // Storing each json item in variable
    String id = c.getString(TAG_ID);
    String person = c.getString(TAG_PERSON);
    // creating new HashMap
    HashMap<String, String> map = new HashMap<String, String>();

    // adding each child node to HashMap key => value
    map.put(TAG_ID, id);
    map.put(TAG_FROM, person);