LibGDX JSON parsing from an API

依然范特西╮ 提交于 2021-01-28 00:36:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!