2015-07-19 83 views
2

我想解析由OpenWeatherMap API返回的JSON,特別是thisLibGDX JSON解析從API

我正在使用this post中建議的方法,即在返回的JSON中使用與參數名稱相同的類變量創建類。它適用於除「雨」和「雪」中的「3h」之外的所有參數。

顯然,我不能在Java中創建一個名爲3h的變量,並且類變量必須具有相同的名稱。

有沒有辦法如何正確解析它(包括「3h」)?

+0

爲什麼類變量必須具有相同的名稱?你使用什麼類/工具來反序列化JSON?發佈一些代碼。 – FWeigl

+0

@Ascorbin我無法發佈兩個以上的鏈接,對不起。我正在使用LibGDX,所以這是 - https://github.com/libgdx/libgdx/wiki/Reading-&-writing-JSON 我包裝信息的類是在原始帖子中。 – 8311697110108101122

+0

使用地圖? http://stackoverflow.com/questions/19028616/how-to-read-json-variable-that-use-number-for-its-name-with-gson – noumenal

回答

2

所以,有幾個解決方案:

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