json2

接下来看一段复杂的json文本,要求用java代码解析当前的天气 和 未来三天的天气:

{

            "count": 1,
            "created": "2016-06-24T05:44:43Z",
            "lang": "null",
            "results":
            {
                "channel":
                {
                    "units":
                    {
                        "distance": "km",
                        "pressure": "mb",
                        "speed": "km/h",
                        "temperature": "C"
                    },
                    "title": "Yahoo! Weather - Changsha, Hunan, CN",
                    "link": "http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-12686154/",
                    "description": "Yahoo! Weather for Changsha, Hunan, CN",
                    "language": "en-us",
                    "lastBuildDate": "Fri, 24 Jun 2016 01:44 PM CST",
                    "ttl": "60",
                    "location":
                    {
                        "city": "Changsha",
                        "country": "China",
                        "region": " Hunan"
                    },
                    "wind":
                    {
                        "chill": "88",
                        "direction": "293",
                        "speed": "22.53"
                    },
                    "atmosphere":
                    {
                        "humidity": "90",
                        "pressure": "33796.17",
                        "rising": "0",
                        "visibility": "24.94"
                    },
                    "astronomy":
                    {
                        "sunrise": "5:33 am",
                        "sunset": "7:28 pm"
                    },
                    "image":
                    {
                        "title": "Yahoo! Weather",
                        "width": "142",
                        "height": "18",
                        "link": "http://weather.yahoo.com",
                        "url": "http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif"
                    },
                    "item":
                    {
                        "title": "Conditions for Changsha, Hunan, CN at 01:00 PM CST",
                        "lat": "28.148609",
                        "long": "112.996727",
                        "link": "http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-12686154/",
                        "pubDate": "Fri, 24 Jun 2016 01:00 PM CST",
                        "condition":
                        {
                            "code": "47",
                            "date": "Fri, 24 Jun 2016 01:00 PM CST",
                            "temp": "30",
                            "text": "Scattered Thunderstorms" },
                        "forecast":
                        [
                            {
                                "code": "4",
                                "date": "24 Jun 2016",
                                "day": "Fri",
                                "high": "31",
                                "low": "25",
                                "text": "Thunderstorms" },
                            {
                                "code": "26",
                                "date": "25 Jun 2016",
                                "day": "Sat",
                                "high": "24",
                                "low": "22",
                                "text": "Cloudy" },
                            {
                                "code": "47",
                                "date": "26 Jun 2016",
                                "day": "Sun",
                                "high": "28",
                                "low": "21",
                                "text": "Scattered Thunderstorms" },
                            {
                                "code": "4",
                                "date": "27 Jun 2016",
                                "day": "Mon",
                                "high": "32",
                                "low": "23",
                                "text": "Thunderstorms" },
                            {
                                "code": "4",
                                "date": "28 Jun 2016",
                                "day": "Tue",
                                "high": "33",
                                "low": "25",
                                "text": "Thunderstorms" },
                            {
                                "code": "4",
                                "date": "29 Jun 2016",
                                "day": "Wed",
                                "high": "31",
                                "low": "27",
                                "text": "Thunderstorms" },
                            {
                                "code": "4",
                                "date": "30 Jun 2016",
                                "day": "Thu",
                                "high": "29",
                                "low": "27",
                                "text": "Thunderstorms" },
                            {
                                "code": "4",
                                "date": "01 Jul 2016",
                                "day": "Fri",
                                "high": "30",
                                "low": "27",
                                "text": "Thunderstorms" },
                            {
                                "code": "4",
                                "date": "02 Jul 2016",
                                "day": "Sat",
                                "high": "29",
                                "low": "26",
                                "text": "Thunderstorms" },
                            {
                                "code": "4",
                                "date": "03 Jul 2016",
                                "day": "Sun",
                                "high": "29",
                                "low": "25",
                                "text": "Thunderstorms" }
                        ],

                        "guid":
                        {
                            "isPermaLink": "false" }
                    }
                }
            }

    }

可以看到 ,数据比较复杂,嵌套层数很多。有两种办法,一种是一层一层地找,另外一种是用json-path,JSONpath.read(json字符串,”$.第一层.第二层…”)
代码如下:

//解析json    
    public static void parseJson(String json) {
        //String t1="{'hi':'nihao'}";

        //这样一层一层地找很麻烦
        JSONObject jsonObject=new JSONObject().fromObject(json);
        //System.out.println(jsonObject);
        JSONObject j2=(JSONObject) jsonObject.get("results");
        //System.out.println(j2);
        //String count=jsonObject.getString("count");
        //System.out.println(count);
        JSONObject j3=(JSONObject) j2.get("channel");
        //System.out.println(j3);       
        JSONObject j4=(JSONObject) j3.get("item");
        //System.out.println(j4);   
        JSONObject j5=(JSONObject) j4.get("condition"); 
        //System.out.println(j5);   
        System.out.println("当前长沙市温度:"+j5.getInt("temp"));
        System.out.println("当前长沙市天气描述:"+j5.getString("text"));

        JSONArray jsonArray=j4.getJSONArray("forecast");
        //System.out.println(jsonArray);

        System.out.println("未来三天天气情况:");

        for(int i=1;i<=3;i++)
        {

            JSONObject j=jsonArray.getJSONObject(i);
            System.out.println(j.getString("date")+":最高温度"+j.getInt("high")+",最低温度:"+j.getInt("low")+",描述:"+j.getString("text"));
        }


        //用json-path更简单
        System.out.println("-------------json path-----------------");
        //JSONObject jObject=JsonPath.read(json, "$.results.channel.item.condition");返回类型需为linkedhashmap
        LinkedHashMap<String, Object> condition=JsonPath.read(json, "$.results.channel.item.condition");
        //$:根目录
        //System.out.println(condition);
        System.out.println("当前长沙市温度:"+condition.get("temp"));
        System.out.println("当前长沙市天气描述:"+condition.get("text"));
        //System.out.println(jObject);
        //JSONArray array=JsonPath.read(json, "$.results.channel.item.forecast");
        //System.out.println(JsonPath.parse(jsonObject));
        net.minidev.json.JSONArray array=JsonPath.read(json, "$.results.channel.item.forecast");
        //LinkedHashMap<String, Object> myjJsonObject=(LinkedHashMap<String, Object>) array.get(0);
        //System.out.println(myjJsonObject);
        //System.out.println(array);
        //LinkedHashMap<String, Object> item=JsonPath.read(json, "$.results.channel.item");
        //System.out.println(item);
        for(int i=1;i<=3;i++)
        {

            LinkedHashMap<String, Object> j=(LinkedHashMap<String, Object>) array.get(i);
            System.out.println(j.get("date")+":最高温度"+j.get("high")+",最低温度:"+j.get("low")+",描述:"+j.get("text"));
        }
    }
This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or ' '), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值