Java 如何在JSONObject中获得一个JSONObject片段,并带有一个参数?在爪哇
我想在JSON中返回一个称为“批处理”的特定对象。它有一个批次ID和多个问题。问题有问题ID、名称和标记。 下面是一个JSON示例:Java 如何在JSONObject中获得一个JSONObject片段,并带有一个参数?在爪哇,java,json,iterator,Java,Json,Iterator,我想在JSON中返回一个称为“批处理”的特定对象。它有一个批次ID和多个问题。问题有问题ID、名称和标记。 下面是一个JSON示例: { "batch" { "b_id" : "5", "question" : { "q_id" : "3", "name" : "foo", "mark" : "3" } "question" : { "q_id" : "4", "name" :
{
"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不是很有经验,但我尝试使用迭代器,因为它有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;
}
publicjsonobjectgetbatch(intid)抛出SQLException、ClassNotFoundException、jsoneexception{
JSONObject batches=GetAllBatchs();//这是上面提到的JSONObject
迭代器keys=batches.keys();//我从另一个StackOverflow答案中获取的内容
while(keys.hasNext()){
字符串键=(字符串)键。下一步();
if(batches.get(key)instanceof JSONObject){
//这里我不知道!
//如果发现b_id=5的值,则返回该特定批次!
}
}
返回null;
}
现在我不知道在迭代器本身之间放什么。如果有人能帮助我,我将不胜感激。您上面的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;
}
使用:json-20140107.jar进行测试
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));
}