过去几天我一直在玩这个游戏,我希望有人能够对这个问题有所了解。将JSON数据保存到C#自定义对象中
我有我创建了这个自定义对象:
public class WorldInformation
{
public string ID { get; set; }
public string name { get; set; }
}
这JSON数据:
string world = "[{\"id\":\"1016\",\"name\":\"Sea of Sorrows\"}, {\"id\":\"1008\",\"name\":\"Jade Quarry\"},{\"id\":\"1017\",\"name\":\"Tarnished Coast\"},{\"id\":\"1006\",\"name\":\"Sorrow's Furnace\"},{\"id\":\"2014\",\"name\":\"Gunnar's Hold\"}]";
,我可以通过反序列化它成功地保存在我的自定义对象中的数据:
List<WorldInformation> worlds = JsonConvert.DeserializeObject<List<WorldInformation>>(world);
但...
个当我创建这样
public class EventItems
{
public string World_ID { get; set; }
public string Map_ID { get; set; }
public string Event_ID { get; set; }
public string State { get; set; }
}
一个自定义对象,并有JSON数据是这样的:
string eventItem = "{\"events\":[{\"world_id\":1011,\"map_id\":50,\"event_id\":\"BAD81BA0-60CF-4F3B-A341-57C426085D48\",\"state\":\"Active\"},{\"world_id\":1011,\"map_id\":50,\"event_id\":\"330BE72A-5254-4036-ACB6-7AEED05A521C\",\"state\":\"Active\"},{\"world_id\":1011,\"map_id\":21,\"event_id\":\"0AC71429-406B-4B16-9F2F-9342097A50AD\",\"state\":\"Preparation\"},{\"world_id\":1011,\"map_id\":21,\"event_id\":\"C20D9004-DF6A-4217-BF25-7D6B5788A94C\",\"state\":\"Success\"}]}";
我得到一个错误,当我尝试反序列化
List<EventItems> events = JsonConvert.DeserializeObject<List<EventItems>>(eventItem);
错误我得到的消息是:
无法反序列化当前的JSON对象(例如{“name”:“value”})类型为'System.Collections.Generic.List`1 [WebApplication1.EventItems]',因为该类型需要JSON数组(例如[1,2,3])才能正确地反序列化。
要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,以使其成为正常的.NET类型(例如,不是像整数这样的基本类型,不是像数组或List的集合类型),可以从JSON对象反序列化。 JsonObjectAttribute也可以添加到类型中,以强制它从JSON对象反序列化。
路径“事件”,第1行,位置10
谢谢,Romoku。这工作完美 – Robert
我很高兴你发现它有帮助! – Romoku