为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕哥6287543 2022-07-14 09:50:17
我正在尝试解析 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中获取错误作为异常
查看完整描述

1 回答

?
忽然笑

TA贡献1806条经验 获得超5个赞

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;


@Data

public class ExclusionListWrapper {


    @JsonProperty("ExclusionList")

    private ExclusionList exclusionList;


    @Data

    class ExclusionList {

        List<String>    serviceLevel;

        List<String>    item;


    }


    public static void main(String[] args) throws Exception {

        String data = "{\"ExclusionList\" : {\"serviceLevel\" : [\"sl1\",\"sl2\",\"sl3\"], \"item\" : [\"ABC\",\"XYZ\"]}}";

        ObjectMapper mapper = new ObjectMapper();

        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        ExclusionListWrapper exclusionlistWrapper = mapper.readValue(data, ExclusionListWrapper.class);

        List<String> excllist = exclusionlistWrapper.getExclusionList().getServiceLevel();

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

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

        }

    }


}


查看完整回答
反对 回复 2022-07-14
  • 1 回答
  • 0 关注
  • 107 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号