gpt4 book ai didi

c# - 如何修复无法反序列化 JSON,与 key "1", "2"混淆

转载 作者:太空宇宙 更新时间:2023-11-03 22:30:15 28 4
gpt4 key购买 nike

我对编号(键)新闻列表(数组)感到困惑

json 字符串是有效的,在 nodeJS 中它设法输出我需要的值。

JSON 字符串原样

{
"newsalert": [{
"newslist": {
"1": {
"newsid": "4321",
"headline": "Great White Shark Found",
"newscode": "GWS",
"newstime": "10:04:32"
},
"2": {
"newsid": "8031",
"headline": "Polar Bear Escaped",
"newscode": "PBE",
"newstime": "09:28:03"
}
}
}]
}

C#代码

class MainNews {
public Dictionary<string, newslist[]> newsalert { get; set; }
}

class newslist {
public int newsid { get; set; }
public string headline{ get; set; }
public string newscode { get; set; }
public string newstime { get; set; }
}

static void ShowObject(MainNews obj) {
foreach (var item in obj.news.Values.ElementAt(0)) {
MessageBox.Show(item.headline);
}
}

private void BtnTest_Click(object sender, RoutedEventArgs e) {
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
var xnews = JsonConvert.DeserializeObject<MainNews>(jsonstring);
ShowObject(xnews);
}

错误

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array because the type requires a JSON object

最佳答案

您在根目录和词典之间缺少一个步骤。
newsalert 是具有属性名称 newslist 的对象的集合。
这是你的字典。

public class MainNews
{
public List<NewAlert> newsalert { get; set; }
}

public class NewAlert
{
public Dictionary<int, NewItem> newslist { get; set; }
}

public class NewItem
{
public string newsid { get; set; }
public string headline { get; set; }
public string newscode { get; set; }
public string newstime { get; set; }
}

你可以简单地:

string input = @"{
""newsalert"": [{
""newslist"": {
""1"": {
""newsid"": ""4321"",
""headline"": ""Great White Shark Found"",
""newscode"": ""GWS"",
""newstime"": ""10:04:32""
},
""2"": {
""newsid"": ""8031"",
""headline"": ""Polar Bear Escaped"",
""newscode"": ""PBE"",
""newstime"": ""09:28:03""
}
}
}]
}";


var result = JsonConvert.DeserializeObject<MainNews>(input);
result.newsalert.SelectMany(x=> x.newslist.Values).Dump();

现场演示:https://dotnetfiddle.net/Ar5ocP

关于c# - 如何修复无法反序列化 JSON,与 key "1", "2"混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58233129/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com