c# 객체 및 Json 직렬 변환

1888 단어 json
      json       framework2.0     

  :     Newtonsoft.Json.dll,       

using System;

using System.IO;

using System.Text;

using Newtonsoft.Json;



namespace OfflineAcceptControl.UCTools

{

    public class JsonTools

    {

        //          Json 

        public static string ObjectToJson(object obj)

        {

           return JavaScriptConvert.SerializeObject(obj);

        }

        //    Json       

        public static object JsonToObject(string jsonString, object obj)

        {

           return JavaScriptConvert.DeserializeObject(jsonString, obj.GetType());

        }

    }

}





      json       framework3.5     

    :System.Runtime.Serialization,System.ServiceModel.Web

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Text;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Json;



namespace CrjIIOfflineAccept.CrjIITools

{

    public class JsonTools

    {

        //          Json 

        public static string ObjectToJson(object obj)

        {

           DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());

           MemoryStream stream = new MemoryStream();

           serializer.WriteObject(stream, obj);

           byte[] dataBytes = new byte[stream.Length];

           stream.Position = 0;

           stream.Read(dataBytes, 0, (int)stream.Length);

           return Encoding.UTF8.GetString(dataBytes);

        }

        //    Json       

        public static object JsonToObject(string jsonString, object obj)

        {

           DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());

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

           return serializer.ReadObject(mStream);

        }

    }

}


좋은 웹페이지 즐겨찾기