Как распарсить сложный Json в List

349
28 сентября 2021, 08:00

От сервера приходит вот такой json

jQuery171010123521258160095_1571660062730({"status":"ok","combinations":[{"barCode":"999859546144","number":"999859546144","numbers":[17,20,31,42,52,2,10,21,30,88,3,44,64,72,83,11,29,48,79,86,24,49,53,61,85,7,15,39,58,78],"favouriteNumbers":[]},{"barCode":"999848737003","number":"999848737003","numbers":[7,26,34,79,82,12,31,42,51,69,1,14,23,48,81,10,21,40,58,80,18,29,37,50,68,3,35,62,78,89],"favouriteNumbers":[]},{"barCode":"999860332802","number":"999860332802","numbers":[4,25,40,53,90,17,50,67,71,82,18,37,49,69,74,1,15,20,39,54,8,10,46,68,73,33,45,55,79,88],"favouriteNumbers":[]},{"barCode":"999860339777","number":"999860339777","numbers":[6,32,66,71,80,2,15,22,35,89,29,48,51,62,74,11,23,31,56,88,10,27,34,49,77,1,44,55,68,86],"favouriteNumbers":[]},{"barCode":"999859916773","number":"999859916773","numbers":[16,21,32,67,74,2,35,42,71,83,6,29,47,57,88,23,39,40,54,78,19,28,37,59,63,8,46,60,75,80],"favouriteNumbers":[]},{"barCode":"999859234230","number":"999859234230","numbers":[14,31,57,77,82,4,28,30,52,65,2,22,45,67,88,7,10,32,48,51,18,29,39,54,62,26,44,60,74,86],"favouriteNumbers":[]},{"barCode":"999848753896","number":"999848753896","numbers":[11,38,55,76,81,19,33,48,62,90,5,28,43,63,79,3,27,64,73,89,6,15,26,36,88,18,32,47,58,67],"favouriteNumbers":[]},{"barCode":"999848749752","number":"999848749752","numbers":[39,42,59,69,76,9,13,26,51,81,16,23,32,77,90,5,25,54,70,88,1,17,47,63,85,21,30,43,65,79],"favouriteNumbers":[]},{"barCode":"999848765453","number":"999848765453","numbers":[4,17,49,77,83,9,25,31,59,87,11,43,55,69,71,6,12,36,79,84,3,21,32,41,61,24,51,67,78,81],"favouriteNumbers":[]},{"barCode":"999859919264","number":"999859919264","numbers":[23,48,66,78,84,6,17,30,50,87,25,32,58,69,75,19,42,68,71,86,1,11,27,36,51,2,28,39,40,55],"favouriteNumbers":[]}]});

мне нужно получит из него List

класс Ticket

public class Ticket {
    Long number;
    public Long getNumber() {
        return number;
    }
    public void setNumber(Long number) {
        this.number = number;
    }
    public Set<Long> getNumbers() {
        return numbers;
    }
    public void setNumbers(Set<Long> numbers) {
        this.numbers = numbers;
    }
    Set<Long> numbers;
}
Answer 1

Распарсить можно ,например, используя json-simple библиотеку. http://www.java2s.com/Code/Jar/j/Downloadjsonsimple111jar.htm

Вы дали json с невалидным форматом.Уберите JQuery... Вот решение вашей задачи:

Вот результат вызова toString() одного обьекта Ticket. 
Ticket [barCode=999859546144, number=999859546144, numbers=[17, 20, 31, 42, 52, 2, 10, 21, 30, 88, 3, 44, 64, 72, 83, 11, 29, 48, 79, 86, 24, 49, 53, 61, 85, 7, 15, 39, 58, 78], favouriteNumbers=[17, 20, 31, 42, 52, 2, 10, 21, 30, 88, 3, 44, 64, 72, 83, 11, 29, 48, 79, 86, 24, 49, 53, 61, 85, 7, 15, 39, 58, 78]]

1.Классы

Main.java
Parser.java
Ticket.java

Их код

Main.java

public class Main {
public static void main(String[] args) {
    String json = "{\"status\":\"ok\",\"combinations\":[{\"barCode\":\"999859546144\",\"number\":\"999859546144\",\"numbers\":[17,20,31,42,52,2,10,21,30,88,3,44,64,72,83,11,29,48,79,86,24,49,53,61,85,7,15,39,58,78],\"favouriteNumbers\":[]},{\"barCode\":\"999848737003\",\"number\":\"999848737003\",\"numbers\":[7,26,34,79,82,12,31,42,51,69,1,14,23,48,81,10,21,40,58,80,18,29,37,50,68,3,35,62,78,89],\"favouriteNumbers\":[]},{\"barCode\":\"999860332802\",\"number\":\"999860332802\",\"numbers\":[4,25,40,53,90,17,50,67,71,82,18,37,49,69,74,1,15,20,39,54,8,10,46,68,73,33,45,55,79,88],\"favouriteNumbers\":[]},{\"barCode\":\"999860339777\",\"number\":\"999860339777\",\"numbers\":[6,32,66,71,80,2,15,22,35,89,29,48,51,62,74,11,23,31,56,88,10,27,34,49,77,1,44,55,68,86],\"favouriteNumbers\":[]},{\"barCode\":\"999859916773\",\"number\":\"999859916773\",\"numbers\":[16,21,32,67,74,2,35,42,71,83,6,29,47,57,88,23,39,40,54,78,19,28,37,59,63,8,46,60,75,80],\"favouriteNumbers\":[]},{\"barCode\":\"999859234230\",\"number\":\"999859234230\",\"numbers\":[14,31,57,77,82,4,28,30,52,65,2,22,45,67,88,7,10,32,48,51,18,29,39,54,62,26,44,60,74,86],\"favouriteNumbers\":[]},{\"barCode\":\"999848753896\",\"number\":\"999848753896\",\"numbers\":[11,38,55,76,81,19,33,48,62,90,5,28,43,63,79,3,27,64,73,89,6,15,26,36,88,18,32,47,58,67],\"favouriteNumbers\":[]},{\"barCode\":\"999848749752\",\"number\":\"999848749752\",\"numbers\":[39,42,59,69,76,9,13,26,51,81,16,23,32,77,90,5,25,54,70,88,1,17,47,63,85,21,30,43,65,79],\"favouriteNumbers\":[]},{\"barCode\":\"999848765453\",\"number\":\"999848765453\",\"numbers\":[4,17,49,77,83,9,25,31,59,87,11,43,55,69,71,6,12,36,79,84,3,21,32,41,61,24,51,67,78,81],\"favouriteNumbers\":[]},{\"barCode\":\"999859919264\",\"number\":\"999859919264\",\"numbers\":[23,48,66,78,84,6,17,30,50,87,25,32,58,69,75,19,42,68,71,86,1,11,27,36,51,2,28,39,40,55],\"favouriteNumbers\":[]}]}";
    Parser parser = new Parser(json);
    parser.doParse();
    if (parser.isOk()) {
        List<Ticket> tickets = parser.getResult();
        for (Iterator<Ticket> iterator = tickets.iterator(); iterator.hasNext();)
            System.out.println(iterator.next().toString());
    }
}

}

Parser.java

public class Parser {
private String json;
private boolean isOk;
private List<Ticket> result = new ArrayList<>();
private JSONParser parser = new JSONParser();
public Parser(String json) {
    this.json = json;
}
public void setJSON(String json) {
    this.json = json;
    isOk = false;
    result.clear();
}
public void doParse() {
    try {
        Object obj = parser.parse(json);
        JSONObject jsonObj = (JSONObject) obj;
        String status = (String) jsonObj.get("status");
        switch (status) {
        case "ok":
            isOk = true;
            break;
        default:
            isOk = false;
            break;
        }
        if (!isOk) {
            System.out.println("status is false");
            return;
        }
        JSONArray combinations = (JSONArray) jsonObj.get("combinations");
        Iterator combinations_iterator = combinations.iterator();
        Ticket ticket = null;
        while (combinations_iterator.hasNext()) {
            JSONObject tick_obj = (JSONObject) combinations_iterator.next();
            // combinations -> barCode & number
            long barCode = Long.parseLong((String) tick_obj.get("barCode"));
            long number = Long.parseLong((String) tick_obj.get("number"));
            ticket = new Ticket(barCode, number);
            // combinations -> numbers
            JSONArray numbers = (JSONArray) tick_obj.get("numbers");
            Iterator numbers_iterator = numbers.iterator();
            while (numbers_iterator.hasNext()) {
                Long num = (Long) numbers_iterator.next();
                ticket.getNumbers().add(num);
            }
            JSONArray fav_numbers = (JSONArray) tick_obj.get("numbers");
            Iterator fav_numbers_iterator = fav_numbers.iterator();
            while (fav_numbers_iterator.hasNext()) {
                Long num = (Long) fav_numbers_iterator.next();
                ticket.getFavouriteNumbers().add(num);
            }
            result.add(ticket);
        }
    } catch (org.json.simple.parser.ParseException e) {
        e.printStackTrace();
    }
}
public List<Ticket> getResult() {
    return this.result;
}
public boolean isOk() {
    return this.isOk;
}

Ticket.java

public class Ticket {
private long barCode;
private long number;
private List<Long> numbers = new ArrayList<>();
private List<Long> favouriteNumbers = new ArrayList<>();
public Ticket(long barCode, long number) {
    this.barCode = barCode;
    this.number = number;
}
public long getBarCode() {
    return barCode;
}
public void setBarCode(long barCode) {
    this.barCode = barCode;
}
public long getNumber() {
    return number;
}
public void setNumber(long number) {
    this.number = number;
}
public List<Long> getNumbers() {
    return numbers;
}
public void setNumbers(List<Long> numbers) {
    this.numbers = numbers;
}
public List<Long> getFavouriteNumbers() {
    return favouriteNumbers;
}
public void setFavouriteNumbers(List<Long> favouriteNumbers) {
    this.favouriteNumbers = favouriteNumbers;
}
@Override
public String toString() {
    return "Ticket [barCode=" + barCode + ", number=" + number + ", numbers=" + numbers + ", favouriteNumbers="
            + favouriteNumbers + "]";
}
READ ALSO
Как лучше хранить и загружать изображения в приложение на Android?

Как лучше хранить и загружать изображения в приложение на Android?

Пишу небольшое приложение магазина одежды(первое более менее похожее на приложение)Вопрос следующий: Как правильно хранить изображения...

244
Алгоритм поиска кластеров в двумерном массиве

Алгоритм поиска кластеров в двумерном массиве

Всем привет, в упор не вижу решение задачиСобственно в чем задача: дан 2-мерный массив целых чисел A[N, M] (1<=N<=1000, 1<=M<=1000, 0<=A[_, _]<=1000)

129
Смена обоев через приложение на android

Смена обоев через приложение на android

Подскажите пожалуйста, есть ли возможность написать приложение на Android, которое автоматически меняло обои на смартфоне без помощи пользователя?

122
Jackson сериализация по id

Jackson сериализация по id

Есть 2 обьекта

84