从API解析LibGDX JSON [英] LibGDX JSON parsing from an API

查看:58
本文介绍了从API解析LibGDX JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析OpenWeatherMap API返回的JSON,特别是.

I'm trying to parse a JSON returned by OpenWeatherMap API, specifically this.

我正在使用这篇文章中建议的方法,即使用带有名称与返回的JSON中的参数相同.它适用于除"rain"和"snow"中的"3h"以外的所有参数.

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".

显然,我无法在 Java 中创建名为 3h 的变量,并且类变量必须具有相同的名称.

Obviously, I can't create a variable named 3h in Java and the class variable has to have the same name.

有没有一种方法可以正确地解析所有内容(包括"3h")?

Is there a way how to parse it all (including the "3h") properly?

推荐答案

因此,解决方案很少:

  • 使用ObjectMap(链接,网址为最后)
  • 自己解析(不得已)
  • 或我目前正在成功雇用的人:

  • 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);
/*...*/

访问值:

double windSpeed = jsonWrapper.wind.speed;

和包装类:

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;
}

这篇关于从API解析LibGDX JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆