问题
I'm trying to parse a JSON returned by OpenWeatherMap API, specifically this.
I'm using the approach suggested in this post, that is create classes with class variables with names same as parameters in the returned JSON. It works for all parameters except the "3h" one in "rain" and "snow".
Obviously, I can't create a variable named 3h in Java and the class variable has to have the same name.
Is there a way how to parse it all (including the "3h") properly?
回答1:
So, there were few solutions:
- Use an ObjectMap (link, at the very end)
- Parse it myself (the last resort)
or the one I'm currently employing successfully:
/*...*/ Json json = new Json(); String jsonStr = /* JSON here */ jsonStr = jsonStr.replace("\"3h\"", "\"_3h\""); JSONWrapper jsonWrapper = json.fromJson(JSONWrapper.class, jsonStr); /*...*/
Accessing values:
double windSpeed = jsonWrapper.wind.speed;
And the wrapper class:
import java.util.ArrayList;
public class JSONWrapper {
Coord coord;
ArrayList<Weather> weather;
String base;
MainJ main;
Wind wind;
Clouds clouds;
Rain rain;
Snow snow;
int dt;
Sys sys;
int id;
String name;
int cod;
String message;
Visibility visibility;
}
class Weather {
int id;
String main;
String description;
String icon;
}
class Coord {
double lon;
double lat;
}
class Visibility {
String value;
}
class MainJ {
double temp;
int pressure;
int humidity;
double temp_min;
double temp_max;
}
class Wind {
double speed;
int deg;
}
class Clouds {
int all;
}
class Snow {
int _3h;
}
class Rain {
int _3h;
}
class Sys {
int type;
int id;
double message;
String country;
int sunrise;
int sunset;
}
来源:https://stackoverflow.com/questions/31503410/libgdx-json-parsing-from-an-api