json 反序列化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using uzai.tools;
using Newtonsoft.Json;

namespace CodeTest.test8
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //json 反序列化1
            string jsonString1 = "{\"Age\":28,\"Name\":\"张三\"}";
            Person p1 = JsonHelper.JsonDeserialize<Person>(jsonString1);

            //json 反序列化2
            string jsonString = "[{treeId:13938,treeName:\"海洋水手号\"},{treeId:19955,treeName:\"内舱房\",imgId:19603,imgName:\"内舱房\"},{treeId:17929,treeName:\"济州蓝色海岸\"}]";
            List<tree> p = Newtonsoft.Json.JsonConvert.DeserializeObject<List<tree>>(jsonString);
        }

        

       public class Person
       {
            public int Age { get; set; }

            public string Name { get; set; }

        }

        public class tree
        {

            public int treeId { get; set; }

            public string treeName { get; set; }

            public int imgId { get; set; }

            public string imgName { get; set; }

        }


    }
}


方法1使用的 Jsonhelper


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;


namespace uzai.tools
{
    /// <summary>

    /// JSON序列化和反序列化辅助类

    /// </summary>

    public class JsonHelper
    {

        /// <summary>

        /// JSON序列化

        /// </summary>

        public static string JsonSerializer<T>(T t)
        {

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));

            MemoryStream ms = new MemoryStream();

            ser.WriteObject(ms, t);

            string jsonString = Encoding.UTF8.GetString(ms.ToArray());

            ms.Close();

            return jsonString;

        }



        /// <summary>

        /// JSON反序列化

        /// </summary>

        public static T JsonDeserialize<T>(string jsonString)
        {

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));

            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));

            T obj = (T)ser.ReadObject(ms);

            return obj;

        }
    }
}

方法2 需要引用  Newtonsoft.Json.dll

下载地址:

http://download.csdn.net/detail/suntanyong88/7335929

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值