JSONHelp json解析成类,类解析成string

时间:2023-03-08 16:48:26
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text; namespace Share
{
/// <summary>
/// 解析JSON,仿Javascript风格
/// </summary>
public static class JSONHelp
{ public static T parse<T>(string jsonString)
{
try
{
LogHelp.WriteLog("返回json:" + jsonString);
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
}
}
catch (Exception ex)
{
LogHelp.WriteLog(ex.Message+ex.StackTrace+":"+ jsonString);
return default(T);
}
} public static string stringify(object jsonObject)
{
try
{
using (var ms = new MemoryStream())
{
new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
catch (Exception ex)
{
LogHelp.WriteLog(ex.Message+ex.StackTrace);;
return "";
}
}
}
}