【问题标题】:LibGDX JSON parsing from an API从 API 解析 LibGDX JSON
【发布时间】:2015-07-19 16:34:01
【问题描述】:

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

我正在使用this post 中建议的方法,即创建具有类变量的类,其名称与返回的 JSON 中的参数相同。它适用于除“rain”和“snow”中的“3h”之外的所有参数。

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

有没有办法正确解析所有内容(包括“3h”)?

【问题讨论】:

  • 为什么类变量必须同名?您使用什么类/工具来反序列化 JSON?贴一些代码。
  • @Ascorbin 我不能发布超过两个链接,对不起。我正在使用 LibGDX,所以它是这个 - github.com/libgdx/libgdx/wiki/Reading-&-writing-JSON 我包装信息的类在原始帖子中。
  • @noumenal 是的,这也是可能的。 LibGDX 就像this 一样(在最后)。如果没有更简单的选择,我愿意这样做。
  • @EpicPandaForce 是的,看来我得自己解析了。

标签: android json libgdx


【解决方案1】:

因此,解决方案很少:

  • 使用 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;

以及包装类:

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

【讨论】:

    猜你喜欢
    • 2014-06-17
    • 2016-07-19
    • 2015-03-31
    • 2011-11-30
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    相关资源
    最近更新 更多