从Java中的List 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])的值?

谢谢

  1. 记录是具有方法get(int)List<JSONObject>类型,但没有方法get(String)
  2. Double.parseDouble采用String参数,而不是Double

尝试:

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]     >值:12,34 5,67 89,01 1,40-ID = 43560139  -PinArray for'43560139'= [43.56,1.39,43.57,1.4]     >值: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>

最新更新