使用JSON.Net轉換常見物件
程式碼如下
- 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);
- Deserialize a DataTable/Serialize a DataSet
DataSet ds = JsonConvert.DeserializeObject<DataSet>("{\"Table1\":" + sJson + "}");
string sJson = JsonConvert.SerializeObject(ds.tables[0], Formatting.Indented);
- 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 });
- Deserialize/Serialize a Dictionary
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(sJson);
string json = JsonConvert.SerializeObject(dicObj, Formatting.Indented);
- JSON字串不出現換行符號
string sJson = JsonConvert.SerializeObject(ds, Formatting.None);
沒有留言:
張貼留言