Необходимо проанализировать массивы JSON, которые находятся внутри объекта JSON в JAVA - PullRequest
0 голосов
/ 01 марта 2019

Я пытаюсь проанализировать данные JSON, присутствующие в datas.json. Мне нужно проанализировать данные исключения с использованием классов Beans / POJO. Данные JSON выглядят следующим образом:
"ExclusionList" : { "serviceLevel" : ["sl1","sl2","sl3"], "item" : ["ABC","XYZ"] } }

Я создал классы POJO для ExclusionList, но не могу получить и распечатать в консоли класса 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 Ответ

0 голосов
/ 01 марта 2019
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));
        }
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...