Xml, Json serialization

Json to object:

  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"));

  Calling method: string JsonStr=Jsons["Key"].ToString();

Object to 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);
  }

  Calling method: String Json= ObjectToJson(T);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324992979&siteId=291194637