需要添加引用:System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using:

using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;

序列化为字符串:

   1: public static string SerializeToJsonString( object objectToSerialize )
   2: {
   3:     using( MemoryStream ms = new MemoryStream() )
   4:     {
   5:         DataContractJsonSerializer serializer =
   6:                 new DataContractJsonSerializer( objectToSerialize.GetType() );
   7:         serializer.WriteObject( ms, objectToSerialize );
   8:         ms.Position = 0;
   9: 
  10:         using( StreamReader reader = new StreamReader( ms ) )
  11:         {
  12:             return reader.ReadToEnd();
  13:         }
  14:     }
  15: }

反序列化:

   1: public static T Deserialize<T>( string jsonString )
   2: {
   3:     using( MemoryStream ms = new MemoryStream( Encoding.Unicode.GetBytes( jsonString ) ) )
   4:     {
   5:         DataContractJsonSerializer serializer = new DataContractJsonSerializer( typeof( T ) );
   6: 
   7:         return ( T )serializer.ReadObject( ms );
   8:     }
   9: }

相关文章:

  • 2021-08-28
  • 2022-02-26
  • 2021-11-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-30
  • 2022-01-30
  • 2022-12-23
  • 2022-12-23
  • 2021-07-13
  • 2021-12-31
相关资源
相似解决方案