首页 .NET/Web JsonToObject序列化方法

JsonToObject序列化方法

作者:胡同里的砖头 围观群众:959 更新于:2017-03-15

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }



    public static T JSONToObject2<T>(string jsonText)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        try
        {
            return jss.Deserialize<T>(jsonText);
        }
        catch (Exception ex)
        {
            throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
        }
    }


    public static T JSONToObject<T>(string jsonString)
    {
        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
        {
            return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
        }
    }
    string str = "[{\"Name\":\"lj\",\"Age\":12,\"Alive\":true,\"FavoriteFilms\":[\"Up\",\"Avatar\"],\"Child\":null},{\"Name\":\"cy\",\"Age\":28,\"Alive\":false,\"FavoriteFilms\":null,\"Child\":{\"Name\":\"lj\",\"Age\":12,\"Alive\":true,\"FavoriteFilms\":[\"Up\",\"Avatar\"],\"Child\":null}}]";

    string str3 = "[{\"Name\":\"lj\",\"Age\":12,\"Alive\":true},{\"Name\":\"xx\",\"Age\":11,\"Alive\":true}]";

    string str2 = "[{'Name':'815bb899-8d70-4745-b799-7e68840a2b34','Age':13,'Alive':true},{'Name':'111222','Age':1555,'Alive':false}]";

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public bool Alive { get; set; }
        public string[] FavoriteFilms { get; set; }
        public Person Child { get; set; }
    }
    public class Person2
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public bool Alive { get; set; }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        
        List<Person2> ps = JsonHelper.JsonStrToObject<List<Person2>>(str2);
        //List<Person2> persons = JSONToObject2<List<Person2>>(str2);

        Response.Write(ps[0].Name + "——" + ps[0].Age);
    }
}



------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;

/// <summary>
/// JsonHelper 的摘要说明
/// </summary>
public static class JsonHelper
{
    //public JsonHelper()
    //{
        public static T JSONToObject2<T>(string jsonText)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        try
        {
            return jss.Deserialize<T>(jsonText);
        }
        catch (Exception ex)
        {
            throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
        }
    }


        public static T JSONToObject<T>(string jsonString)
    {
        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
        {
            return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
        }
    }


    //Json to Object
    public static T JsonStrToObject<T>(this string input)
    {
        //JavaScriptSerializer serializer = new JavaScriptSerializer();
        //serializer.MaxJsonLength = 999999999;
        //input = Regex.Replace(input, @"\\/Date\((\d+)\)\\/", match => { DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value)); dt = dt.ToLocalTime(); return dt.ToString("yyyy-MM-dd HH:mm:ss"); });
        //return serializer.Deserialize<T>(input);

        var json = Regex.Replace(
            input,
            @":new Date\((\d+)\)",
            match =>
            {
                var datetime = new DateTime(0x7b2, 1, 1).AddMilliseconds(long.Parse(match.Groups[1].Value)).ToLocalTime();
                var output = ":\"" + datetime.ToString("yyyy-MM-ddTHH:mm:ss.fff") + "\"";
                return output;
            });
        var serializer = new JavaScriptSerializer() { MaxJsonLength = 0x3b9ac9ff };

        json = Regex.Replace(json, @"\\/Date\((\d+)\)\\/", match => { DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value)); dt = dt.ToLocalTime(); return dt.ToString("yyyy-MM-dd HH:mm:ss"); });

        var entity = serializer.Deserialize<T>(json);
        return entity;
    }

    //}
}

  • 本文标题: JsonToObject序列化方法
  • 文章分类:【.NET/Web】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8