我是json的新手。我有一个url,我传递值和返回的数据是json。我需要从这个url反序列化json,然后将其绑定到asp.net中的列表视图控件。这就是json数据的样子。
{"records":[{"record":{"Ch_ID":"27","User_id":"1","Ch_Name":"test1","Ch_Description":"test1description","Ch_Starttime":""}},{"record":{"Ch_ID":"29","User_id":"1","Ch_Name":"w","Ch_Description":"ww","Ch_Starttime":"12"}},{"record":{"Ch_ID":"30","User_id":"1","Ch_Name":"qq","Ch_Description":"qqqdescription","Ch_Starttime":"1222"}},{"record":{"Ch_ID":"31","User_id":"1","Ch_Name":"v","Ch_Description":"vv","Ch_Starttime":"1"}},{"record":{"Ch_ID":"32","User_id":"1","Ch_Name":"n","Ch_Description":"nnnn","Ch_Starttime":"111"}}]}
有人知道我该怎么做吗?我已经尝试了json.net,但它给我错误
Json。. NET确实支持通过其内置的DataTableConverter
对DataTable
进行反序列化,但是它希望JSON被格式化为数组,如下所示:
[
{
"Ch_ID": "27",
"User_id": "1",
// Other fields
},
{
"Ch_ID": "29",
"User_id": "1",
// Other fields
},
// Other records
]
你的JSON被格式化如下:
{
"records": [
{
"record": {
"Ch_ID": "27",
"User_id": "1",
// Other fields
}
},
{
"record": {
"Ch_ID": "29",
"User_id": "1",
// Other fields
}
},
// Other records
]
}
您可以将实际的JSON转换为JSON所需的格式。. NET使用自定义JsonConverter
:
public class RecordDataTableConverter : Newtonsoft.Json.Converters.DataTableConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
if (reader.TokenType == JsonToken.StartObject)
{
var token = JToken.Load(reader);
token = new JArray(token.SelectTokens("records[*].record"));
using (var subReader = token.CreateReader())
{
while (subReader.TokenType == JsonToken.None)
subReader.Read();
return base.ReadJson(subReader, objectType, existingValue, serializer); // Use base class to convert
}
}
else
{
return base.ReadJson(reader, objectType, existingValue, serializer);
}
}
}
并按如下方式使用:
var json = GetJson();
var settings = new JsonSerializerSettings
{
Converters = new[] { new RecordDataTableConverter() },
};
var table = JsonConvert.DeserializeObject<DataTable>(json, settings);
样本小提琴。