我多次尝试解码由嵌套数组组成的嵌套JSON字符串,我用GSON()
来做。并且它有效,但问题是关于这个数组中的对象不能从json解码,所以我想要你的帮助:
JSON字符串:
{ "data" : { "current_condition" : [ { "cloudcover" : "75",
"humidity" : "87",
"observation_time" : "03:16 AM",
"precipMM" : "1.5",
"pressure" : "991",
"temp_C" : "11",
"temp_F" : "52",
"visibility" : "7",
"weatherCode" : "293",
"weatherDesc" : [ { "value" : "Patchy light rain" } ],
"weatherIconUrl" : [ { "value" : "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0033_cloudy_with_light_rain_night.png" } ],
"winddir16Point" : "SSW",
"winddirDegree" : "210",
"windspeedKmph" : "30",
"windspeedMiles" : "19"
} ],
"request" : [ { "query" : "London, United Kingdom",
"type" : "City"
} ],
"weather" : [ { "date" : "2014-01-03",
"precipMM" : "6.9",
"tempMaxC" : "10",
"tempMaxF" : "50",
"tempMinC" : "5",
"tempMinF" : "41",
"weatherCode" : "293",
"weatherDesc" : [ { "value" : "Patchy light rain" } ],
"weatherIconUrl" : [ { "value" : "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0017_cloudy_with_light_rain.png" } ],
"winddir16Point" : "SW",
"winddirDegree" : "220",
"winddirection" : "SW",
"windspeedKmph" : "33",
"windspeedMiles" : "21"
} ]
} }
我的代码解码这个JSON:
HashMap HashMap = new Gson().fromJson(json, HashMap.class);
及其输出:
{data = {request = [{query = London,United Kingdom,type = City}], current_condition = [{cloudcover = 75,湿度= 87,观察时间= 03:16 AM,precipMM = 1.5,压力= 991,temp_C = 11,temp_F = 52,能见度= 7, weatherCode = 293,weatherDesc = [{value = Patchy light rain}], weatherIconUrl = [{值= http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0033_cloudy_with_light_rain_night.png}], winddir16Point = SSW,winddirDegree = 210,windspeedKmph = 30, windspeedMiles = 19}],weather = [{date = 2014-01-03,precipMM = 6.9, tempMaxC = 10,tempMaxF = 50,tempMinC = 5,tempMinF = 41,weatherCode = 293, weatherDesc = [{value = Patchy light rain}], weatherIconUrl = [{值= http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0017_cloudy_with_light_rain.png}], winddir16Point = SW,winddirDegree = 220,winddirection = SW, windspeedKmph = 33,windspeedMiles = 21}]}}
所以我想要一个理想的方法让我能够输入这个嵌套的HashMap数组及其值,因为我的方法不能让我能够从这个数组中调用嵌套值
谢谢,
答案 0 :(得分:1)
因为字符串代表另一个Hashmap中的Hashmap,你可以使用像
这样的东西HashMap<String, HashMap> hashMap = new Gson().fromJson(json, HashMap.class);
答案 1 :(得分:0)
在我使用这种方法之后它才有效:
Type type = new TypeToken< HashMap<String, HashMap<String, ArrayList<com.google.gson.internal.LinkedTreeMap>>>>() {}.getType();
HashMap<String, HashMap<String, ArrayList<com.google.gson.internal.LinkedTreeMap>>> hashMap = new Gson().fromJson(API.getJSON(), type);
com.google.gson.internal.LinkedTreeMap hash = hashMap.get("data").get("current_condition").get(0);
System.out.println(" "+hash.get("humidity")+" ");
我知道你的答案和我的第一种方法都是正确的,但正如我告诉你的那样,我想进入这个Json里面的条目嵌套数组列表