首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web Service >

解析多条数据的json解决思路

2013-01-02 
解析多条数据的json[{id:1,classify:水分,remark:,nutritionName:,nfcId:1},{id:2,cla

解析多条数据的json
[{"id":1,"classify":"水分","remark":"","nutritionName":"","nfcId":1},{"id":2,"classify":"蛋白质","remark":"","nutritionName":"氨基酸","nfcId":2},{"id":3,"classify":"糖","remark":"","nutritionName":"","nfcId":3},{"id":4,"classify":"维生素","remark":"","nutritionName":"","nfcId":4},{"id":5,"classify":"无机盐","remark":"","nutritionName":"","nfcId":5},{"id":6,"classify":"油脂","remark":"","nutritionName":"","nfcId":6},{"id":7,"classify":"蛋白质","remark":"","nutritionName":"赖氨酸","nfcId":2}]

这个json怎么解析??????
[解决办法]
首先,可以定义一个DataContract,如下
  [DataContract]
    public class DataContruct
    {
        [DataMember]
        internal string total;

        [DataMember]
        internal List<rootData> root;
    }

    [DataContract]
    public class rootData
    {
        [DataMember]
        internal string ZFLSH;

        [DataMember]
        internal string BMBH;


        [DataMember]
        internal string XMBH;

        [DataMember]
        internal string GZH;

        [DataMember]
        internal string XM;

        [DataMember]
        internal string JE;

        [DataMember]
        internal string ZFLB;

        [DataMember]
        internal string RQ;


        [DataMember]
        internal string BZ;

        [DataMember]
        internal string XTLB;

    }
然后这样解析,如下:
  MemoryStream stream = new MemoryStream();
            DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(DataContruct));
            StreamWriter wr = new StreamWriter(stream);
            wr.Write(Str_JsonData);
            wr.Flush();
            stream.Position = 0;
            Object obj = ser2.ReadObject(stream);
            DataContruct p2 = (DataContruct)obj;

            List<rootData> rdlist = p2.root;
            if (rdlist.Count() == 1)


            {
                rootData rd = rdlist[0];
                zflsh = rd.ZFLSH.Trim();
                fzrbh = rd.GZH.Trim();
                bmbh = rd.BMBH.Trim();
                xmbh = rd.XMBH.Trim();
                fkje = rd.JE.Trim();
                gwrq = rd.RQ.Trim();
                sblb = rd.ZFLB.Trim();
                sclbbh = rd.XTLB.Trim();
                bz = rd.BZ.Trim();
              }
上面是我的一个例子代码,你改一下应该就能用,希望对你有帮助!
[解决办法]
通用?在静态语言里,类定义需要提前准备的。

要么你就反序列化成 List<Dictionary<string, string>> 好了。
[解决办法]
http://www.cnblogs.com/txw1958/archive/2012/08/01/csharp-json.html

Newtonsoft.Json 解析

[解决办法]
吼吼,C#也支持

Deserialize JSON into C# dynamic object?
http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object/3806407#3806407

看来得去研究一下C#的dynamic功能了。

热点排行