Answer the question
In order to leave comments, you need to log in
Read json from file?
I'm trying to read json but I'm getting an error
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 5 path $
{
"tickets": [{
"origin": "VVO",
"origin_name": "Владивосток",
"destination": "TLV",
"destination_name": "Тель-Авив",
"departure_date": "12.05.18",
"departure_time": "16:20",
"arrival_date": "12.05.18",
"arrival_time": "22:10",
"carrier": "TK",
"stops": 3,
"price": 12400
},
{
"origin": "VVO",
"origin_name": "Владивосток",
"destination": "TLV",
"destination_name": "Тель-Авив",
"departure_date": "12.05.18",
"departure_time": "6:10",
"arrival_date": "12.05.18",
"arrival_time": "16:15",
"carrier": "S7",
"stops": 0,
"price": 17400
}]
}
public class POJOTickets
{
String origin;
String origin_name;
String destination;
String destination_name;
String departure_date;
String departure_time;
String arrival_date;
String arrival_time;
String carrier;
String stops;
String price;
public class Main
{
public static void main(String[] args)
{
File input=new File("D:\\tickets.json");
try
{
JsonElement fileElement= JsonParser.parseReader(new FileReader(input));
JsonObject fileObjact=fileElement.getAsJsonObject();
JsonArray jsonArrayOfTickets=fileObjact.get("tickets").getAsJsonArray();
List<POJOTickets> tickets=new ArrayList<>();
for(JsonElement ticketsElement:jsonArrayOfTickets)
{
JsonObject ticketsJsonObjact=ticketsElement.getAsJsonObject();
String origin=ticketsJsonObjact.get("origin").getAsString();
String origin_name=ticketsJsonObjact.get("origin_name").getAsString();
String destination=ticketsJsonObjact.get("destination").getAsString();
String destination_name=ticketsJsonObjact.get("destination_name").getAsString();
String departure_date=ticketsJsonObjact.get("departure_date").getAsString();
String departure_time=ticketsJsonObjact.get("departure_time").getAsString();
String arrival_date=ticketsJsonObjact.get("arrival_date").getAsString();
String arrival_time=ticketsJsonObjact.get("arrival_time").getAsString();
String carrier=ticketsJsonObjact.get("carrier").getAsString();
String stops=ticketsJsonObjact.get("stops").getAsString();
String price=ticketsJsonObjact.get("price").getAsString();
POJOTickets ticket=new POJOTickets(
origin,
origin_name,
destination,
destination_name,
departure_date,
departure_time,
arrival_date,
arrival_time,
carrier,
stops,
price);
tickets.add(ticket);
}
System.out.println(tickets);
}
catch (Exception e)
{
System.err.println(e);
}
}
}
Answer the question
In order to leave comments, you need to log in
JSON:
"stops": 3,
"price": 12400
String stops;
String price;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question