本文介绍了读取DataTable时出现意外的JSON令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下json字符串:
{
Orders:[{
SubOrderNo: 0582715,
ItemNo: 20415541,
ItemType: ART,
ItemName:鱼,
TemplateName : TP1234,
ObjectType: MPP,
ObjectId: PE1234,
SalesStartDate: 2018-08-01,
InfoText:一些伪文本。直到稍后将其替换为一些令人敬畏的文本。快乐鱼!,
附件:null,
TemplateImage:null,
ApprovedBy :我,
ExpectedDeliveryDate: 2017-10-20,
上下文:null,
TemplateDescription:null,
ColorStatus: 0,
spArticles:[]
}],
JsonOrders:空
}
我已经在json lint上对此进行了验证,因此它是有效的json。
我有以下代码:
public s tatic DataTable jsonStringToTable(string jsonContent)
{
DataTable dt = JsonConvert.DeserializeObject< DataTable>(jsonContent);
return dt;
}
运行此命令时,出现错误:
读取DataTable时出现意外的JSON令牌。应该是StartArray,得到了StartObject。路径,第1行,位置1。
任何能说出我为什么不能转换我的人的人将json转换为数据表?
解决方案
使用这个,我希望它能起作用。 b
///需要上面的.net Framework 4.5。
公共静态DataTable表(字符串jsonContent)
{
var jsonLinq = JObject.Parse(jsonContent);
//使用Linq
查找第一个数组var srcArray = jsonLinq.Descendants()。Where(d => d是JArray).First();
var trgArray = new JArray();
foreach(srcArray.Children< JObject>()中的JObject行)
{
var cleanRow = new JObject();
foreach(row.Properties()中的JProperty列)
{
//如果(column.Value为JValue)
{
cleanRow.Add(column.Name,column.Value);
}
}
trgArray.Add(cleanRow);
}
返回JsonConvert.DeserializeObject< DataTable>(trgArray.ToString());
}
I have the following json string:
{
"Orders": [{
"SubOrderNo": "0582715",
"ItemNo": "20415541",
"ItemType": "ART",
"ItemName": "Fish",
"TemplateName": "TP1234",
"ObjectType": "MPP",
"ObjectId": "PE1234",
"SalesStartDate": "2018-08-01",
"InfoText": "Some dummy text. This till be replaced later with some awesome text instead. Happy Fish!",
"Attachment": null,
"TemplateImage": null,
"ApprovedBy": "Me",
"ExpectedDeliveryDate": "2017-10-20",
"Context": null,
"TemplateDescription": null,
"ColorStatus": 0,
"spArticles": []
}],
"JsonOrders": null
}
I have validate this on json lint, so it's valid json.
I have the following code:
public static DataTable jsonStringToTable(string jsonContent)
{
DataTable dt = JsonConvert.DeserializeObject<DataTable>(jsonContent);
return dt;
}
When I run this, I get the error:
Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.
Anyone who can tell why I can't convert my json to datatable?
解决方案
Use this one, I hope it will work.
//require .net Framework 4.5 above.
public static DataTable Tabulate(string jsonContent)
{
var jsonLinq = JObject.Parse(jsonContent);
// Find the first array using Linq
var srcArray = jsonLinq.Descendants().Where(d => d is JArray).First();
var trgArray = new JArray();
foreach (JObject row in srcArray.Children<JObject>())
{
var cleanRow = new JObject();
foreach (JProperty column in row.Properties())
{
// Only include JValue types
if (column.Value is JValue)
{
cleanRow.Add(column.Name, column.Value);
}
}
trgArray.Add(cleanRow);
}
return JsonConvert.DeserializeObject<DataTable>(trgArray.ToString());
}
这篇关于读取DataTable时出现意外的JSON令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!