【发布时间】:2014-01-03 03:29:20
【问题描述】:
我多次尝试解码由嵌套数组组成的嵌套 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,observation_time=03:16 AM, precipMM=1.5, 压力=991, temp_C=11, temp_F=52, 能见度=7, weatherCode=293, weatherDesc=[{value=小雨}], 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}],天气=[{日期=2014-01-03,precipMM=6.9, tempMaxC=10,tempMaxF=50,tempMinC=5,tempMinF=41,weatherCode=293, weatherDesc=[{value=零星小雨}], 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 数组及其值,因为我的方法不能让我从这个数组中调用嵌套值
谢谢,
【问题讨论】:
-
您的代码应该可以正常工作;您只需要将内部对象缓存到 HashMap。
-
查看 json.org 了解 JSON 语法。这很容易理解。
-
要访问内部对象,您只需“剥洋葱”,一次一层。 “数据”为您提供了一个地图,您可以从中访问“当前条件”。这会产生一个包含一个元素的列表,一个包含“cloudcover”、“湿度”、“observation_time”等的地图。
-
(Map) HashMap.get("data")将为您提供代表"data"属性值的地图。
标签: java arraylist hashmap gson