请看一下照片。
我在尝试将JSON字符串转换为列表对象时遇到困难。 经过故障排除后,我发现问题是由于Json索引(Number正在增加而不是按1,2,4,5,6,5601,5611 ..的顺序)。任何人都知道我如何将json转换为升序列表中的对象12345678910 ..(model [0],model 1,model [2],model [3] ....)
using (StreamReader reader = new StreamReader(stream))
{
jsonstr = reader.ReadToEnd();
}
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
List<Notification> model = JsonConvert.DeserializeObject<List<Notification>>(jsonstr, settings).Where(m => m != null).ToList();
错误消息:
Newtonsoft.Json.JsonSerializationException:'无法反序列化当前JSON对象(例如{“ name”:“ value”})为类型'System.Collections.Generic.List`1',因为该类型需要JSON数组(例如[1,2,3])正确反序列化。 要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化类型,使其成为普通的.NET类型(例如,不像整数这样的原始类型,也不像这样的集合类型数组或列表),可以从JSON对象反序列化。还可以将JsonObjectAttribute添加到类型中,以强制其从JSON对象反序列化。 路径'1',第1行,位置5。'
JSON结果
{"1":{"confirmation_status":"Rejected","createDateTime":"2018-08-31 16:58:58.087","logID":1,"notification_message":"\"There is a change request for \"Vital\" to be approved.\"","read_status":"true","recipient":"68d9dffc-b3be-4527-a89a-829b76abf754","sender":"01a94cf4-5df4-4097-b6ea-d929170de1e7","senderDetails":"Adeline Tan "},"6":{"confirmation_status":"Rejected","createDateTime":"2018-08-31 16:58:58.087","logID":6,"notification_message":"\"There is a change request for \"Vital\" to be approved.\"","read_status":"true","recipient":"68d9dffc-b3be-4527-a89a-829b76abf754","sender":"01a94cf4-5df4-4097-b6ea-d929170de1e7","senderDetails":"Adeline Tan "},"5601":{"confirmation_status":"Pending","createDateTime":"2018-08-31 16:58:58.087","logID":5601,"notification_message":"\"There is a change request for \"Vital\" to be approved.\"","read_status":"true","recipient":"68d9dffc-b3be-4527-a89a-829b76abf754","sender":"01a94cf4-5df4-4097-b6ea-d929170de1e7","senderDetails":"Adeline Tan "},"5611":{"confirmation_status":"Pending","createDateTime":"2018-08-31 16:58:58.087","logID":5611,"notification_message":"\"There is a change request for \"Vital\" to be approved.\"","read_status":"true","recipient":"68d9dffc-b3be-4527-a89a-829b76abf754","sender":"01a94cf4-5df4-4097-b6ea-d929170de1e7","senderDetails":"Adeline Tan "}}
通知类别:
public class Notification
{
public string confirmation_status { get; set; }
public string createDateTime { get; set; }
public int logID { get; set; }
public string notification_message { get; set; }
public string read_status { get; set; }
public string recipient { get; set; }
public string sender {get; set; }
public string senderDetails { get; set; }
}
答案 0 :(得分:2)
显示的JSON是对象而不是数组
您最有可能想要
List<Notification> model = JsonConvert.DeserializeObject<Dictionay<string,Notification>>(jsonstr, settings)
.Select(kvp => kvp.Value)
.Where(m => m != null)
.OrderBy(m => m.logID)
.ToList();
将JSON转换为字典并将值提取为所需的类型。