C# 解析json Newtonsoft.Json

Newtonsoft.Json.dll

    public class ErrorInfo {
public error_response error_response { get; set; }
}
public class error_response
{
public string code { get; set; }
public string zh_desc { get; set; }
public string en_desc { get; set; }
}

  

            //嵌套性数据
// {"error_response": {"code":"001","zh_desc":"信息无效"}} //解析方法一: 解析成一个对象实体
ErrorInfo obj = (ErrorInfo)JsonConvert.DeserializeObject(jsonText, typeof(ErrorInfo)); //解析方法二: 解析对象
JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
string code = jo["error_response"]["code"].ToString();
string zone = jo["error_response"]["zh_desc"].ToString();

  

 /// <summary>
/// Json帮助类
/// </summary>
public class JsonHelper
{
private static void InitSetting()
{
Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
{ //日期类型默认格式化处理
setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
//空值处理
setting.NullValueHandling = NullValueHandling.Ignore; return setting;
});
} /// <summary>
/// 将对象序列化为JSON格式
/// </summary>
/// <param name="o">对象</param>
/// <returns>json字符串</returns>
public static string SerializeObject(object o)
{
InitSetting();
string json = JsonConvert.SerializeObject(o);
return json.Replace("0001/1/1 0:00:00", "");//去除空日期 0001/1/1 0:00:00
}
public static object DeserializeObject(string o)
{
InitSetting();
return JsonConvert.DeserializeObject(o);
}
public static object DeserializeObject(string o, Type type)
{
InitSetting();
return JsonConvert.DeserializeObject(o, type);
} /// <summary>
/// 解析JSON字符串生成对象实体
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param>
/// <returns>对象实体</returns>
public static T DeserializeObject<T>(string json) where T : class
{
InitSetting();
object o = JsonConvert.DeserializeObject(json, typeof(T));
T t = o as T;
return t;
} }

JsonHelper

上一篇:BZOJ1915: [Usaco2010 Open]奶牛的跳格子游戏


下一篇:webRTC中语音降噪模块ANS细节详解(四)