使用JSON.Net轉換常見物件

Designed by Freepik
此篇紀錄如何使用JSON.Net轉換常見的物件
圖片來源Designed by Freepik


程式碼如下
  1. Deserialize/Serialize a DataSet
DataSet ds = JsonConvert.DeserializeObject<DataSet>(sJson);

string sJson = JsonConvert.SerializeObject(ds, Formatting.Indented);

//JSON字串不出現換行符號
string sJson = JsonConvert.SerializeObject(ds, Formatting.None);

  1. Deserialize a DataTable/Serialize a DataSet
DataSet ds = JsonConvert.DeserializeObject<DataSet>("{\"Table1\":" + sJson + "}");

string sJson = JsonConvert.SerializeObject(ds.tables[0], Formatting.Indented);

  1. Deserialize/Serialize a List obj
List<RFCData> _listRFCData = JsonConvert.DeserializeObject<List<RFCData>>(sJson);
↓obj
RFCData _rFCData = JsonConvert.DeserializeObject<RFCData>(sJson);

string sJson = JsonConvert.SerializeObject(_listRFCData, Formatting.Indented);
string sJson = JsonConvert.SerializeObject(_rFCData, Formatting.Indented);

//忽略null欄位
string sJson = JsonConvert.SerializeObject(_listRFCData, Formatting.Indented,
          new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

  1. Deserialize/Serialize a Dictionary
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(sJson);

string json = JsonConvert.SerializeObject(dicObj, Formatting.Indented);

  1. JSON字串不出現換行符號
string sJson = JsonConvert.SerializeObject(ds, Formatting.None);

沒有留言:

張貼留言

技術提供:Blogger.