Asp.net Json數據解析的一種思路


在日常的編碼中,經常會遇到JSON類型的數據,有簡單的,也有復雜的。對於簡單的,我們可以用正則等匹配,但是一旦遇到復雜的,就比較難辦了。

數據分析

目前手頭上需要制作一個天氣預報功能,現成的接口已經有了。我隨便輸入一個城市,然后出現了如下的信息:

{"wdata":{"cityName":"鶴壁",
          "location":{"lat":"35.62",
                      "lng":"114.18"},
          "today":"2013-9-12 10:30:00",
          "sevDays":[{"date":"2013-9-12 20:00:00","Tmax":"28","weatherID":"02轉01","windDir":"0","windPower":"0","Tmin":"18"},
                     {"date":"2013-9-13 20:00:00","Tmax":"33","weatherID":"00","windDir":"0","windPower":"0","Tmin":"18"},
                     {"date":"2013-9-14 20:00:00","Tmax":"35","weatherID":"00","windDir":"0","windPower":"0","Tmin":"19"},
                     {"date":"2013-9-15 20:00:00","Tmax":"27","weatherID":"01","windDir":"0","windPower":"0","Tmin":"16"},
                     {"date":"2013-9-16 20:00:00","Tmax":"25","weatherID":"01","windDir":"0","windPower":"0","Tmin":"17"},
                     {"date":"2013-9-17 20:00:00","Tmax":"26","weatherID":"02","windDir":"0","windPower":"0","Tmin":"18"},
                     {"date":"2013-9-18 20:00:00","Tmax":"27","weatherID":"02轉07","windDir":"0","windPower":"0","Tmin":"16"}],
          "zhishu":[{"value":"2","name":"CY"},
                              {"value":"0","name":"ZS"},
                              {"value":"8","name":"FH"},
                              {"value":"2","name":"ZWX"},
                              {"value":"4","name":"KQWR"},
                              {"value":"2","name":"LY"},
                              {"value":"1","name":"JT"},
                              {"value":"1","name":"GM"},
                              {"value":"1","name":"SSD"}],
          "currentMessage":{"reportTime":"2013-9-12 13:00:00",
                                            "weatherID":"02",
                                            "temperature":"27",
                                            "windDir":"4",
                                            "windPower":"0",
                                            "humidity":"69.0",
                                            "visibility":"8",
                                            "pressure":"1012.2",
                                            "sunrise":"6:01",
                                            "sunset":"18:38"}
          }
}

這段JSON數據結構比一般的要復雜那么一點,不過從其結構來看:

第一層應該是wdata。

第二層是cityName(城市名稱),location(經緯度),today(當前時間),sevDays(后續天氣),zhishu(指數),currentMessage(當前預報信息)。

第三層是:location下面的lat,lng;sevDays下面的date,Tmax,weatherID,windDir,windPower,Tmin; 然后是zhishu下面的value 和 name;最后是currentMessage下面的reportTime,weatherID,temperature,windDir,windPower,humidity,visibility,pressure,sunrise,sunset信息:

所以,總共說來,這個JSON數據總共就三層。

解析方式

那么,如何來解析呢?

其實,我們完全可以從最底層的結構分析起來,然后簡歷相關的類,最后把這些建立的類組合成類似json數據的結構就可以了。

這里,最底層就是第三層,我們開始建立起相關的類對象:

對於sevDays下的項目, 建立如下類:

using System;

namespace Nxt.Common.Weather
{
   public  class DateReleation
    {
        //sevDays
        public DateTime date { get; set; }
        public int Tmax { get; set; }
        public string weatherID { get; set; }
        public int windDir { get; set; }
        public int windPower { get; set; }
        public int Tmin { get; set; }
    }
}

對於zhishu下的項目,建立的類如下:

namespace Nxt.Common.Weather
{
    public class IndexPoint
    {
        //zhishu
        public int value { get; set; }
        public string name { get; set; }
    }
}

對於currentMessage下的項目,建立的類如下:

using System;

namespace Nxt.Common.Weather
{
    public class CurrentMessage
    {
        //currentMessage
        public DateTime reportTime { get; set; }
        public string weatherID {get;set;}
        public double temperature { get; set; }
        public string windDir { get; set; }
        public string windPower { get; set; }
        public double humidity { get; set; }
        public string visibility { get; set; }
        public double pressure { get; set; }
        public string sunrise { get; set; }
        public string sunset { get; set; }
    }
}

對於location下面的項目,建立的類如下:

namespace Nxt.Common.Weather
{
   public  class Location
    {
        //location
        public string lat { get; set; }
        public string lng { get; set; }
    }
}

 

當第三層的都建立完畢后,現在來建立第二層,第二層的對象如上面所述,但是需要注意的是,sevDays,zhishu都是可以有多條記錄的 ,所以我們得用List對象來保存。

using System;
using System.Collections.Generic;

namespace Nxt.Common.Weather
{
    public class WeatherMain
    {
        //wdata
        public string cityName { get; set; }
        public Location location { get; set; }
        public DateTime today { get; set; }
        public List<DateReleation> sevDays { get; set; }
        public List<IndexPoint> zhishu { get; set; }
        public CurrentMessage currentMessage { get; set; }

        public WeatherMain()
        {
            sevDays = new List<DateReleation>();
            zhishu = new List<IndexPoint>();
        }
    }
}

上面的代碼是依據JSON數據的結構而建立的,這樣能夠最大程度避免數據的不准確性。
最后,建立頂層的類:

namespace Nxt.Common.Weather
{
    public class Daemon
    {
        public WeatherMain wdata { get; set; }
     }
}

這樣,我們的類結構就建立完畢了。

最后審查一下我們建立的類結構,是不是和JSON數據的組織結構是一樣的呢?

如果是一樣的,讓我們進入下一步:

using System;
using System.IO;
using System.Net;
using System.Web.Script.Serialization;
using Nxt.Common.Weather;
using System.Text;

namespace Nxt.Web.Code
{
    public class WeatherDaemon
    {
        public Daemon GetWeather(string areaName)
        {
            string url = "http://weather.****.net/Weather/getWeather.php?area=" + areaName;
            WebRequest request = WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();

            string weatherData = string.Empty;
            if (dataStream != null)
            {
                try
                {
                    using (StreamReader reader = new StreamReader(dataStream, Encoding.UTF8))
                    {
                        weatherData = reader.ReadToEnd();
                    }
                }
                catch (OutOfMemoryException oe)
                {
                    throw new Exception(oe.Data.ToString());
                }
                catch (IOException ie)
                {
                    throw new Exception(ie.Data.ToString());
                }
            }

            if (!String.IsNullOrEmpty(weatherData))
            {
 JavaScriptSerializer ser = new JavaScriptSerializer(); Daemon main = ser.Deserialize<Daemon>(weatherData); return main;             }
            return null;
        }
    }
}

請注意圖中黃色部分,(使用JavaScriptSerializer,我們需要引用System.web.extensions.)
最后看看結果,我們是不是得到了想要的數據呢?


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM