Xml,Json序列化

Json到对象:

  using System.Runtime.Serialization.Json;

  public static T JsonAndObject<T>(string Json)
  where T : new()
  {
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(Json)))
    {
      T jsonObject = (T)ser.ReadObject(ms);
      return jsonObject;
    }

  }

  调用方式: List<T> list = AnalyzeXml.JsonAndObject<List<T>>(Json);  

  JObject Jsons = (JObject)JsonConvert.DeserializeObject(Json, Type.GetType("System.Data.UTF-8"));

  调用方式:string JsonStr=Jsons["Key"].ToString();

对象到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);
  }

  调用方式:String Json= ObjectToJson(T);

猜你喜欢

转载自www.cnblogs.com/BoyStyle/p/8966193.html