1. 程式人生 > >Newtonsoft.Json的使用

Newtonsoft.Json的使用

在使用Newtonsoft.Json時,把傳送資料和接收資料放入同一個Root中。傳送中不包括接收的資料,接收中不包括髮送的資料。如果使用預設的

//object轉json
public static string SerializeObject(object value)
public class SetData
{
    public string ArgId { get; set; }
    public string Value { get; set; }
}

public class ResponseData
{
    /// <summary>
    /// 
    /// </summary>
    public string ArgId { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public string Value { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public string Result { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public string Option { get; set; }
}

public class Root
{
    public SetData SetData { get; set; }
    public ResponseData ResponseData { get; set; }
}

 好在Newtonsoft.Json給出了許多過載函式:

1、public static string SerializeObject(object value)
2、public static string SerializeObject(object value, Formatting formatting)
3、public static string SerializeObject(object value, params JsonConverter[] converters)
4、public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
5、public static string SerializeObject(object value, JsonSerializerSettings settings)
6、public static string SerializeObject(object value, Type type, JsonSerializerSettings settings)
7、public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
8、public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings)

 使用如下方法可以把為null的值過濾掉,轉換成的json中將沒有與null對應的資料結構

var jsonSetting = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
var s = JsonConvert.SerializeObject(root,Formatting.Indented,jsonSetting);