需要在 JAVA 中解析 JSON 对象内部的 JSON ARRAYS

我正在尝试解析 datas.json 中存在的 JSON 数据。我需要使用 Beans/POJO 类解析排除数据。JSON 数据如下:

"ExclusionList" : {

                  "serviceLevel" : ["sl1","sl2","sl3"],

                  "item" : ["ABC","XYZ"]                                                                 }  }


我为 ExclusionList 创建了 POJO 类,但无法在 ECLIPSE IDE.Mypojo 类的控制台中获取和打印:


List<String> serviceLevel;

List<String> item;

//with gettter and setters.

我的主要课程如下:


public static void main(String[] args)

            throws JsonParseException, JsonMappingException, IOException, ParseException, JSONException {

    File jsonFile = new File("C:\\Users\\sameepra\\Videos\\datas.json");

    ObjectMapper mapper = new ObjectMapper();  

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);

    ExclusionList exclusionlist=mapper.readValue(jsonFile,ExclusionList.class);

    List<String> excllist=exclusionlist.getServiceLevel();

    for (int i = 0; i < excllist.size(); i++) {

        System.out.println(excllist.get(i));

    }

}

在线程“main”java.lang.NullPointerException中获取错误作为异常


慕哥6287543
浏览 108回答 1
1回答

忽然笑

You need to wrap your pojo class in another containing an ExclusionList property.Try this. The examples below uses lombok for getters , setters and default constructor.import java.util.List;import com.fasterxml.jackson.annotation.JsonProperty;import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.ObjectMapper;import lombok.Data;@Datapublic class ExclusionListWrapper {&nbsp; &nbsp; @JsonProperty("ExclusionList")&nbsp; &nbsp; private ExclusionList exclusionList;&nbsp; &nbsp; @Data&nbsp; &nbsp; class ExclusionList {&nbsp; &nbsp; &nbsp; &nbsp; List<String>&nbsp; &nbsp; serviceLevel;&nbsp; &nbsp; &nbsp; &nbsp; List<String>&nbsp; &nbsp; item;&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; String data = "{\"ExclusionList\" : {\"serviceLevel\" : [\"sl1\",\"sl2\",\"sl3\"], \"item\" : [\"ABC\",\"XYZ\"]}}";&nbsp; &nbsp; &nbsp; &nbsp; ObjectMapper mapper = new ObjectMapper();&nbsp; &nbsp; &nbsp; &nbsp; mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);&nbsp; &nbsp; &nbsp; &nbsp; ExclusionListWrapper exclusionlistWrapper = mapper.readValue(data, ExclusionListWrapper.class);&nbsp; &nbsp; &nbsp; &nbsp; List<String> excllist = exclusionlistWrapper.getExclusionList().getServiceLevel();&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < excllist.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(excllist.get(i));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java