我正在编写一个小工具来将 json 转换为 csv。首先,我尝试将 json 转换为 Dataset 或 Datatable 但失败。
Json 字符串是:
{
"id1": {
"id": "id11",
"cards": {
"1": {
"id": "test11",
"fingerprint": "test11",
"last4": "test11",
"exp_month": 7,
"exp_year": 2019,
"brand": "test11"
},
"0": {
"id": "test12",
"fingerprint": "test12",
"last4": "test12",
"exp_month": 7,
"exp_year": 2020,
"brand": "Visa"
},
"2": {
"id": "test13",
"fingerprint": "test13",
"last4": "test13",
"exp_month": 8,
"exp_year": 2020,
"brand": "Visa"
}
}
},
"id2": {
"id": "id21",
"cards": {
"1": {
"id": "test21",
"fingerprint": "test21",
"last4": "test21",
"exp_month": 7,
"exp_year": 2019,
"brand": "MC"
},
"0": {
"id": "test22",
"fingerprint": "test22",
"last4": "test5",
"exp_month": 2,
"exp_year": 2020,
"brand": "Visa"
}
}
}
}
我试过了
DataSet ds = JObject.Parse(jsonContent)["root"].ToObject<DataSet>();
DataTable dt = JsonConvert.DeserializeObject<DataTable>(jsonContent);
但它不起作用。第一个给出这个错误:
JsonToCsv.exe 中发生类型为“System.NullReferenceException”的未处理异常
附加信息:未将对象引用设置为对象的实例。
第二个错误:
Newtonsoft.Json.dll 中发生类型为“Newtonsoft.Json.JsonSerializationException”的未处理异常
附加信息:读取数据表时出现意外的 JSON 标记。预期的 StartArray,得到 StartObject。路径 '',第 1 行,位置 1。
任何建议将不胜感激
我设法将 json 解析为一个列表,然后将列表转换为 csv。解析json到list的代码如下:
public class Card
{
public string ActId { get; set; }
public string CustId { get; set; }
public string Id { get; set; }
public string Fingerprint { get; set; }
public string Last4 { get; set; }
public int Exp_month { get; set; }
public int Exp_year { get; set; }
public string Brand { get; set; }
}
public static List<Card> JsonToCSV(string JsonContent)
{
var ds = JObject.Parse(JsonContent);
var cards = new List<Card>();
foreach (var item in ds)
{
var crds= JObject.Parse(JsonConvert.DeserializeObject(item.Value["cards"].ToString()).ToString());
foreach (var crd in crds)
{
var card =JsonConvert.DeserializeObject<Card>(crd.Value.ToString());
card.ActId= item.Key;
card.CustId= item.Value["id"].ToString();
cards.Add(card);
}
}
return cards;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句