I'm working on android app that should read this json string:
{
"coord":{
"lon":145.77,
"lat":-16.92
},
"weather":[
{
"id":803,
"main":"Clouds",
"description":"broken clouds",
"icon":"04n"
}
],
"base":"cmc stations"
}
Something similar to this.
I can read the "coord"
values successfully using the following method:
public Coordinates readCoordinates(JsonReader reader) throws IOException{
double longitude = 0.0; // lon
double latitude = 0.0; // lat
reader.beginObject();
while (reader.hasNext()){
String nameToRead = reader.nextName();
if(nameToRead.equals("lon")){
longitude = reader.nextDouble();
}else if (nameToRead.equals("lat")){
latitude = reader.nextDouble();
}else {
reader.skipValue();
}
}
reader.endObject();
return (new Coordinates(longitude, latitude));
}
I have a similar method for reading the "weather"
:
public Weather readWeather(JsonReader reader) throws IOException{
int id = 0;
String main = "";
String description = "";
String icon = "";
reader.beginObject();
while (reader.hasNext()){
String nameToRead = reader.nextName();
if(nameToRead.equals("id")){
id = reader.nextInt();
}else if (nameToRead.equals("main")){
main = reader.nextString();
}else if (nameToRead.equals("description")){
description = reader.nextString();
}else if (nameToRead.equals("icon")){
icon = reader.nextString();
}else{
reader.skipValue();
}
}
reader.endObject();
return (new Weather(id, main, description, icon));
}
I keep getting this exception message Expected BEGIN_OBJECT but was BEGIN_ARRAY
If I change reader.beginObject()
to reader.beginArray()
I get the same error. I also tried removing it entirely, and the same error occurred.
I'm assuming this is caused by the introduction of the [
, but I'm not really sure how to fix this. If anyone has a clue please help, I would really appreciate it, thank you.
you are not getting the structure of JSON. after "weather" there array which have only one object. so your code should be
jsonReader.beginArray();
while( jsonReader.hasNext() ) {
jsonReader.beginObject();
while( jsonReader.hasNext() ) {
String nameToRead = reader.nextName();
if(nameToRead.equals("id")){
id = reader.nextInt();
}else if (nameToRead.equals("main")){
main = reader.nextString();
}else if (nameToRead.equals("description")){
description = reader.nextString();
}else if (nameToRead.equals("icon")){
icon = reader.nextString();
else {
jsonReader.skipValue();
}