从JSON对象数组中检索值

时间:2018-08-10 10:48:18

标签: java arrays json

我正在尝试从数组内的对象中检索2个值。 我想到达哪里(任务=更新和taskStatus完成)

对象:

"policies": [
    {
      "policyNumber": "000000000000",
      "policyDetails": {
        "a": "55375",
        "b": "2018-01-20",
        "c": "060",
        "d": "071",
        "e": "IL",
        "f": "012",
        "g": "A",
        "h": "G"
      },
      "tasks": [
        {
          "task": "bills",
          "eligibility": false,
          "intent": null,
          "taskStatus": "Status Unavailable",
          "enrollmentStatus": false,
          "orderNumber": "",
          "reasonDescription": null
        },
        {
          "task": "renewals",
          "eligibility": null,
          "intent": null,
          "taskStatus": "Not Applicable",
          "enrollmentStatus": false,
          "orderNumber": "1",
          "reasonDescription": null
        }
    ]
 }
]

要获得价值,我可以沿线做些什么

if (cPolicy.get().getTasks().getTask("renewals")&& cPolicy.get().getTasks().getTaskStatus("complete") {
}

如何获取值?

1 个答案:

答案 0 :(得分:0)

您的解决方案是,我只是修改了您的完整JSON

JsonNode jsonNode = objectMapper.readTree(from);
jsonNode.get("policies").get(0).get("tasks").get(0).get("eligibility")

示例

import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Json {
    public static void main(String[] args) {
        File from = new File("abc.txt"); 
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode jsonNode = objectMapper.readTree(from);
    System.out.println(jsonNode.get("policies").get(0).get("tasks").get(0).get("eligibility"));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

JSON示例文件abc.txt

  {
"policies": [
    {
      "policyNumber": "000000000000",
      "policyDetails": {
        "a": "55375",
        "b": "2018-01-20",
        "c": "060",
        "d": "071",
        "e": "IL",
        "f": "012",
        "g": "A",
        "h": "G"
      },
      "tasks": [
        {
          "task": "bills",
          "eligibility": false,
          "intent": null,
          "taskStatus": "Status Unavailable",
          "enrollmentStatus": false,
          "orderNumber": "",
          "reasonDescription": null
        },
        {
          "task": "renewals",
          "eligibility": null,
          "intent": null,
          "taskStatus": "Not Applicable",
          "enrollmentStatus": false,
          "orderNumber": "1",
          "reasonDescription": null
        }
    ]
 }
]
}