Вы должны упростить свойство data
до типа: Map<String, Map<String, Flight>>
. Где Flight
POJO
представляет данный рейс. Модель может выглядеть так:
class FlightResponse {
private boolean success;
private Map<String, Map<String, Flight>> data;
private String error;
private String currency;
public Map<String, Flight> getFlatData() {
return data.entrySet()
.stream()
.collect(HashMap::new, (m, e) -> m.putAll(e.getValue()), Map::putAll);
}
// getters, setters, toString
}
class Flight {
private BigDecimal price;
private String airline;
@SerializedName("flight_number")
private int flightNumber;
@SerializedName("departure_at")
private String departureAt;
@SerializedName("return_at")
private String returnAt;
@SerializedName("expires_at")
private String expiresAt;
// getters, setters, toString
}
И пример, как разобрать ваш JSON
:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import java.io.File;
import java.io.FileReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
public class GsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
Gson gson = new GsonBuilder().create();
FlightResponse flightResponse = gson.fromJson(new FileReader(jsonFile), FlightResponse.class);
flightResponse.getFlatData().forEach((k, v) -> {
System.out.println(k + " => " + v);
});
}
}
Над отпечатками кодов:
0 => Flight{price=153, airline='LO', flightNumber=678, departureAt='2019-08-05T17:40:00Z', returnAt='2019-08-20T14:35:00Z', expiresAt='2019-05-24T20:55:02Z'}
1 => Flight{price=126, airline='A3', flightNumber=881, departureAt='2019-11-21T11:00:00Z', returnAt='2019-11-26T16:05:00Z', expiresAt='2019-05-27T13:39:23Z'}
2 => Flight{price=171, airline='KL', flightNumber=900, departureAt='2019-09-12T02:40:00Z', returnAt='2019-09-18T17:30:00Z', expiresAt='2019-05-27T10:40:40Z'}
3 => Flight{price=235, airline='B2', flightNumber=972, departureAt='2019-06-12T07:20:00Z', returnAt='2019-06-18T17:30:00Z', expiresAt='2019-05-26T12:31:22Z'}
4 => Flight{price=596, airline='TK', flightNumber=422, departureAt='2019-06-20T00:10:00Z', returnAt='2019-06-24T13:05:00Z', expiresAt='2019-05-26T08:08:21Z'}
Смотри также: