使用java获取json密钥

时间:2014-11-21 04:38:55

标签: java json

我有一个json对象如何获取所有键,以后如果不对键进行硬编码,我怎样才能获得键值。

  {  
     "A":"M1",
     "Data":[  
        {  
           "B":[  
              {  
                 "B1":"111",
                 "B2":"Warning "

              },
              {  
                 "B1":"222",
                 "B2":"Warning "

              }
           ],
           "C":[  
              {  
                 "c1":"IL2",
                 "c2":"[0.750183,0.00933380975964486]"
              },
              {  
                 "c1":"IL1b",
                 "c2":"[0.750183,-1.5216938335421]"
              }
           ]
        }
     ]
  }

1 个答案:

答案 0 :(得分:0)

试试这个...... 这可能对你有用....

您必须使用JSONObject keys()来获取密钥,然后迭代每个密钥以获取动态值。

代码大致如下:

// searchResult refers to the current element in the array "search_result"
JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();

while(keys.hasNext()) {
    // loop to get the dynamic key
    String currentDynamicKey = (String)keys.next();

    // get the value of the dynamic key
    JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);

    // do something here with the value...
}
相关问题