如何在JSONObject中使用参数获取一块JSONObject?在Java

时间:2016-06-22 18:07:52

标签: java json iterator

我想在我的JSON中返回一个名为' batch'的特定对象。它有批次ID和多个问题。问题有ID,名称和标记。 这是一个JSON示例:

{
  "batch" {
    "b_id" : "5",
    "question" : {
        "q_id" : "3",
        "name" : "foo",
        "mark" : "3"
    }
    "question" : { 
        "q_id" : "4",
        "name" : "bar",
        "mark" : "10"
},

"batch" {//b_id and questions}
}               

我对JSON不是很有经验,但我尝试使用Iterator,因为它有Map接口。这是我的方法:

public JSONObject getBatch(int id) throws SQLException, ClassNotFoundException, JSONException {
JSONObject batches = getAllBatches(); //this is the above mentioned JSONObject
Iterator<?> keys = batches.keys(); //something I took from another StackOverflow answer
while(keys.hasNext()){
    String key = (String) keys.next();
    if(batches.get(key) instanceof JSONObject){
    //Here I don't know!
    //if a value is found with b_id = 5, then return that specific batch!
        }
    }
return null;
}   

现在我不知道在迭代器本身之间放什么。如果有人能帮助我,我非常感激。

1 个答案:

答案 0 :(得分:0)

您上面的示例JSON似乎无效。我认为这就是你所需要的:

{
  "batches" : 
    [
      {
        "b_id" : 5,
        "questions" : 
          [
            {
              "q_id" : "3",
              "name" : "foo",
              "mark" : "3" 
            }, 
            {  
              "q_id" : "4", 
              "name" : "bar", 
              "mark" : "10"
            }
          ] 
      },
      {
        "b_id" : 6,
        "questions" : 
          [
            {
              "q_id" : "4",
              "name" : "foo", 
              "mark" : "4" 
            }, 
            {  
              "q_id" : "5", 
              "name" : "bar", 
              "mark" : "11"
            }
          ] 
       }
    ]
}

以下是获取JSON对象的代码:

public static JSONObject getBatch(JSONObject json, int id) {
    JSONArray batches = json.getJSONArray("batches");
    for (int i=0; i < batches.length(); i++) {
        JSONObject batch = batches.getJSONObject(i);
        Integer batchId = (Integer)batch.get("b_id");
        if (batchId == id) {
            return batch;
        }
    }
    return null;
}

这是我用来测试它的主要方法:

public static void main(String[] args) {
    String input =
        "{\"batches\" : ["
        + "{\"b_id\" : 5,\"questions\" : [{\"q_id\" : \"3\",\"name\" : \"foo\",\"mark\" : \"3\" }, {  \"q_id\" : \"4\", \"name\" : \"bar\", \"mark\" : \"10\"}] },"
        + "{\"b_id\" : 6,\"questions\" : [{\"q_id\" : \"4\",\"name\" : \"foo\",\"mark\" : \"4\" }, {  \"q_id\" : \"5\", \"name\" : \"bar\", \"mark\" : \"11\"}] }"
        + "] "
        + "}";
    JSONObject json = new JSONObject(input);
    System.out.println(getBatch(json, 5));
}

测试:json-20140107.jar