1

我想检索“名称”值并将它们从 Java 中的 JSON 文件存储在 Arraylist 中。我正在使用 JSON 简单库这是我的“file.json”的一个示例:

{
  "111": {

    "customer": {

        "name": "John Do",
        "Height": 5.9,
        "City": "NewYork"
    }

  },
  "222":{

    "customer": {

        "name": "Sean Williams",
        "Height": 6,
        "City": "Los Angeles"
    }
  }
}

ID 号“111”和“222”对我的程序并不重要,它们是随机生成的,所以我无法使用jObject.get(),因为值会不断变化。我尝试为父节点搜索通配符,然后转到子节点 customer,然后name没有找到这样的东西。

到目前为止,这是我的代码:

import java.io.*;
import java.util.ArrayList;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class npTest {

    public static void main(String[] args) throws IOException, ParseException {

        try {
            JSONParser jParser = new JSONParser();
            JSONObject jObject = (JSONObject) jParser.parse(new FileReader("file.json"));

//Notes

    } catch (FileNotFoundException e) {
        System.out.print("File not found!");
    }

}

}

注意:我尝试过的方法需要jObject.get("id"). 我还注意到我无法将 JSONObject 存储在另一个 JSONObject 中,例如:JSONObject parentObj = new JSONObject(jObject.get("111"));

4

2 回答 2

2

JSONObject您可以使用该keySet()方法遍历 a 中的键。然后拔出你"customer"的名字并得到他们的名字。

JSONParser jParser = new JSONParser();
JSONObject jObject = (JSONObject) jParser.parse(new FileReader("c:\\file.json"));

for(Object key : jObject.keySet()) {
    JSONObject customerWrapper = (JSONObject)jObject.get(key);
    JSONObject customer = (JSONObject)customerWrapper.get("customer");
    System.out.println(customer.get("name"));
}
于 2015-06-22T18:24:41.167 回答
0

JSONObject 实现了 Map 接口。因此,您可以使用普通 Java 语法查询所有映射键:

for (Object innnerO : jObject.values()){
  JSONObject customerO = (JSONObject)((JSONObject)innerO).get("customer");
}

注意:这是在没有编译器的情况下写出来的。所以可能有我的错误。

于 2015-06-22T17:38:55.013 回答