在使用Jackson解析JSON时获取特定值

时间:2015-06-12 09:52:17

标签: java json jackson

我有以下JSON:

[  
   {  
      "A":"Lorem Ipsum ",
      "B":"Lorem Ipsum ",
      "C":"Lorem Ipsum ",
      "D":"Lorem Ipsum ",
      "E":"Lorem Ipsum ",
      "F":"Lorem Ipsum ",
      "G":301,
      "H":[  
         {  
            "Lorem Ipsum ":4,
            "Lorem Ipsum ":20,
            "Lorem Ipsum":0
         },
         {  
            "Lorem Ipsum ":5,
            "Lorem Ipsum ":19.2,
            "Lorem Ipsum ":0.8
         },
         {  
            "Lorem Ipsum ":1,
            "Lorem Ipsum ":8,
            "Lorem Ipsum ":4
         },
         {  
            "Lorem Ipsum ":3,
            "Lorem Ipsum ":14.2,
            "Lorem Ipsum ":5.8
         },
         {  
            "Lorem Ipsum ":2,
            "Lorem Ipsum ":20,
            "Lorem Ipsum ":0
         }
      ],
      "I":[  

      ],
      "J":[  

      ],
      "20-01-2014":20,
      "27-01-2014":19.2,
      "30-12-2013":8,
      "13-01-2014":14.2,
      "06-01-2014":20,
      "K":"81.40"
   },
   {  
      "reportKey":"something"
   }
]

我想获取reportKey值,然后将其从文件中删除。但首先我需要访问它,我的代码似乎不起作用:

final ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readValue(rawContentParameters, JsonNode.class);

logger.info("ExportController : generatesExportExcel : parameters: {}", jsonNode.get("reportKey").textValue());

但我得到java.lang.NullPointerException。为什么呢?

SOLUTION:

final ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readValue(rawContentParameters, JsonNode.class);

logger.info("ExportController : generatesExportExcel : parameters: {}", rootNode.get(rootNode.size() - 1).get("reportKey").textValue());

3 个答案:

答案 0 :(得分:6)

您正在访问根JsonNode,就像它是一个对象一样,但它包装在一个数组中。您需要先从数组中提取第二个对象,然后才能访问reportKey

JsonNode array = objectMapper.readValue(rawContentParameters, JsonNode.class);
JsonNode object = array.get(1);
String reportKey = object.get("reportKey").textValue();
logger.info("ExportController : generatesExportExcel : parameters: {}", reportKey);

答案 1 :(得分:2)

首先获取列表中的第二个元素。

jsonNode.get(1).get("reportKey")

答案 2 :(得分:1)

您可以使用org.json库中的GETJSONObject

JSONArray