LibGDX JSON 从 API 解析
LibGDX JSON parsing from an API
我正在尝试解析 OpenWeatherMap API 返回的 JSON,特别是 this。
我正在使用 this post 中建议的方法,即使用 class 变量创建 classes,其名称与返回的 JSON 中的参数相同。它适用于 "rain" 和 "snow" 中除“3h”之外的所有参数。
显然,我不能在 Java 中创建名为 3h 的变量,并且 class 变量必须具有相同的名称。
有没有办法正确解析所有内容(包括“3h”)?
所以,解决方案很少:
- 在最后使用 ObjectMap(link)
- 自己解析(不得已)
或我目前成功雇用的人:
/*...*/
Json json = new Json();
String jsonStr = /* JSON here */
jsonStr = jsonStr.replace("\"3h\"", "\"_3h\"");
JSONWrapper jsonWrapper = json.fromJson(JSONWrapper.class, jsonStr);
/*...*/
访问值:
double windSpeed = jsonWrapper.wind.speed;
和包装器 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;
}
我正在尝试解析 OpenWeatherMap API 返回的 JSON,特别是 this。
我正在使用 this post 中建议的方法,即使用 class 变量创建 classes,其名称与返回的 JSON 中的参数相同。它适用于 "rain" 和 "snow" 中除“3h”之外的所有参数。
显然,我不能在 Java 中创建名为 3h 的变量,并且 class 变量必须具有相同的名称。
有没有办法正确解析所有内容(包括“3h”)?
所以,解决方案很少:
- 在最后使用 ObjectMap(link)
- 自己解析(不得已)
或我目前成功雇用的人:
/*...*/ Json json = new Json(); String jsonStr = /* JSON here */ jsonStr = jsonStr.replace("\"3h\"", "\"_3h\""); JSONWrapper jsonWrapper = json.fromJson(JSONWrapper.class, jsonStr); /*...*/
访问值:
double windSpeed = jsonWrapper.wind.speed;
和包装器 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;
}