从Java中的列表json获取值

时间:2019-02-21 13:58:52

标签: java json

我有一个JSonObject列表

List<JSONObject> records = new ArrayList<JSONObject>();

数据样本:

{
  "ID": 15,
  "Code": {
    "43560139": {
      "Name": [AA, BB],
      "PIN": [43.56, 1.39, 43.57, 1.4],
      "login": ["1C4"],
      "orig": {
       .
       .
       .
}

我想恢复PIN ([43.56, 1.39, 43.57, 1.4]).的值 我在清单上做了一个循环:

for(int i = 0; i < records.size(); i++){
    double pin = Double.parseDouble((Double) records.get("Code").get("PIN"));
}

我知道了

Error:(96, 66) java: incompatible types: java.lang.String cannot be converted to int
Error:(96, 45) java: incompatible types: java.lang.Double cannot be converted to java.lang.String

有人可以帮助我如何恢复PIN ([43.56, 1.39, 43.57, 1.4])的值吗?

谢谢

2 个答案:

答案 0 :(得分:0)

  1. 记录的类型为List<JSONObject>,它具有方法get(int),但没有方法get(String)
  2. Double.parseDouble接受一个String的参数,而不是Double

答案 1 :(得分:0)

尝试:

public static void main(String... args) {
    String JSON_STRING = "{"
            + " \"ID\": 15,\n"
            + "  \"Code\": {\n"
            + "    \"43560139\": {  \"Name\": [\"AA, BB\"],\n\"PIN\": [43.56, 1.39, 43.57, 1.4],\n\"login\": [\"1C4\"]\n },\n"
            + "    \"49876554\": {  \"Name\": [\"CC, DD\"],\n\"PIN\": [12.34, 5.67, 89.01, 1.4],\n\"login\": [\"1C4\"]\n }\n"
            + "    }\n"
            + "}\n";

    List<JSONObject> records = new ArrayList<JSONObject>();
    records.add(new JSONObject(JSON_STRING));

    // for each JSONObject in records...
    for (JSONObject jsonObj : records) {
        JSONObject codeObj = jsonObj.getJSONObject("Code"); // find 'Code'

        // for each 'ID?'/entry in 'Code':
        for (String id : codeObj.keySet()) {
            // eg '43560139':
            System.out.printf("- id=%s%n", id);

            // ... get associated value '{ "Name| :  ... } as object:
            JSONObject idData = codeObj.getJSONObject(id);

            // get 'PIN' as array:
            JSONArray pinArray = idData.getJSONArray("PIN");
            System.out.printf("  - pinArray for '%s'=%s%n", id, pinArray.toString());

            // do something with array:
            System.out.printf("      > values: ");
            pinArray.forEach(pinValue -> {
                System.out.printf("%.2f ", Double.parseDouble(pinValue.toString()));
            });
            System.out.println();
        }
    }
}

输出:

- id=49876554
  - pinArray for '49876554'=[12.34,5.67,89.01,1.4]
      > values: 12,34 5,67 89,01 1,40 
- id=43560139
  - pinArray for '43560139'=[43.56,1.39,43.57,1.4]
      > values: 43,56 1,39 43,57 1,40 

pom.xml:

    <dependencies>
        ... 
        <!-- JSON-java: https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>