栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

打印JSON值

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

打印JSON值

首先,您的json不正确,请使用jsonlint [1]检查json的格式是否正确。

将JSON重新格式化为以下格式,

{    "forecast": {        "txt_forecast": { "date": "8: 00AMMST", "forecastday": [     {         "period": 0,         "icon": "partlycloudy",         "icon_url": "http: //icons-ak.wxug.com/i/c/k/partlycloudy.gif",         "title": "Thursday",         "fcttext": "Partlycloudy.Highof63F.Windslessthan5mph.",         "fcttext_metric": "Partlycloudy.Highof17C.Windslessthan5km/h.",         "pop": "0"     } ]        }    }}

使用以下代码进行解析,

package com.aamir.stackoverflow;import com.google.gson.JsonArray;import com.google.gson.JsonElement;import com.google.gson.JsonObject;import com.google.gson.JsonParser;public class JSonParserStackOverflow {    public static void main(String[] args) {        String request = "{n" +     "    "forecast": {n" +     "        "txt_forecast": {n" +     " "date": "8: 00AMMST",n" +     " "forecastday": [n" +     "     {n" +     "         "period": 0,n" +     "         "icon": "partlycloudy",n" +     "         "icon_url": "http: //icons-ak.wxug.com/i/c/k/partlycloudy.gif",n" +     "         "title": "Thursday",n" +     "         "fcttext": "Partlycloudy.Highof63F.Windslessthan5mph.",n" +     "         "fcttext_metric": "Partlycloudy.Highof17C.Windslessthan5km/h.",n" +     "         "pop": "0"n" +     "     }n" +     " ]n" +     "        }n" +     "    }n" +     "}";        JsonElement weatherJSON = new JsonParser().parse(request);        JsonObject weatherObj = weatherJSON.getAsJsonObject();        JsonObject forecastObj = weatherObj.get("forecast").getAsJsonObject();        JsonObject txt_forecast = forecastObj.get("txt_forecast").getAsJsonObject();        JsonArray forecastDays = txt_forecast.getAsJsonArray("forecastday");        for(JsonElement forecastDay : forecastDays) { System.out.println(forecastDay.getAsJsonObject().get("fcttext").toString());        }    }}

我已经使用Google的GSON [2]库来解析JSON。

[1] http://jsonlint.com/

[2] https://pre.google.com/p/google-gson/



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/428890.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号