需要解析JAVA中JSON对象内部的JSON数组
我正在尝试解析datas.JSON中的JSON数据。我需要使用bean/POJO类解析排除数据。JSON数据如下: 排除名单:{ 服务级别:[sl1、sl2、sl3], 项目:[ABC,XYZ]} 我已经为排除列表创建了POJO类,但无法在ECLIPSE IDE的控制台中获取和打印。Mypojo类:需要解析JAVA中JSON对象内部的JSON数组,java,json,eclipse,Java,Json,Eclipse,我正在尝试解析datas.JSON中的JSON数据。我需要使用bean/POJO类解析排除数据。JSON数据如下: 排除名单:{ 服务级别:[sl1、sl2、sl3], 项目:[ABC,XYZ]} 我已经为排除列表创建了POJO类,但无法在ECLIPSE IDE的控制台中获取和打印。Mypojo类: List<String> serviceLevel; List<String> item; //with gettter and setters. 我的主要课程如下: pu
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));
}
}
在线程主java.lang.NullPointerException中将错误获取为异常是否初始化了List ExcepList??它已在提供的行中初始化为字符串:字符串类型列表*发布控制台日志
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));
}
}
}