C# 物件與JSON相互轉換
阿新 • • 發佈:2019-02-16
需要新增引用:
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 JsonToObjects { public class ObjectToJsons { // 從一個物件資訊生成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); } } }