一、命名空间
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
二、方法
/// <summary>
/// 将对象转换为Json字符串
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ObjToJson(object value)
{
Type type = value.GetType();
Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
json.NullValueHandling = NullValueHandling.Ignore;
json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
System.IO.StringWriter sw = new System.IO.StringWriter();
Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw);
writer.Formatting = Formatting.None;
writer.QuoteChar = '"';
json.Serialize(writer, value);
string output = sw.ToString();
writer.Close();
sw.Close();
return output;
}
/// <summary>
/// 将Json字符串转换为对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonText"></param>
/// <returns></returns>
public static T JsonToObj<T>(string jsonText)
{
Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
System.IO.StringReader sr = new System.IO.StringReader(jsonText);
Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
T result = (T)json.Deserialize(reader, typeof(T));
reader.Close();
return result;
}