【发布时间】:2019-09-09 18:46:35
【问题描述】:
我正在尝试使用 Newtonsoft Json 反序列化以下 json 字符串。我能够成功获取字符串,但是当我尝试使用JsonConvert.DeserializeObject<ServerList>(response, settings); 时,try catch 失败。
[
{"endpoint":"127.0.0.1","id":6,"identifiers":["steam:","license:","xbl:","live:","discord:"],"name":"Blurr","ping":160},
{"endpoint":"127.0.0.1","id":7,"identifiers":["steam:","license:","xbl:","live:","discord:"],"name":"Knight","ping":120}
]
我相信我的问题是因为玩家数组未命名。
我已经为 Users var 尝试过 [JsonProperty("")] 和 [JsonProperty],我也尝试过使用 List 和 Array 而不是 IList。
这里是对象。这可能是完全错误的,我尝试了很多方法。
public class ServerList
{
// I have tried many ways of doing this array/list. This is just the latest way I tried.
[JsonProperty]
public static IList<Player> Users { get; set; }
}
public class Player
{
[JsonProperty("endpoint")]
public static string Endpoint { get; set; }
[JsonProperty("id")]
public static string ServerId { get; set; }
[JsonProperty("identifiers")]
public static IList<string> Identifiers { get; set; }
[JsonProperty("name")]
public static string Name { get; set; }
[JsonProperty("ping")]
public static int Ping { get; set; }
}
我希望得到一个“ServerList”对象,其中包含连接到服务器的所有玩家的列表。
问任何你需要的问题,我不经常使用这种格式的 json。提前谢谢!
错误:从 JsonReader 读取 JObject 时出错。当前 JsonReader 项不是对象:StartArray。路径'',第 1 行,位置 1。
【问题讨论】:
-
你需要删除所有的静态......使用json2csharp.com为你的json获取正确的c#类
-
删除所有静态文件时仍然出现相同的错误。我已将错误添加到主帖子中(当我问这个问题时不知何故错过了它)。我会看看你发布的网站。
-
你的 JSON 是一个数组,所以反序列化为
List<Player>而不是ServerList,即var users = JsonConvert.DeserializeObject<List<Player>>(response, settings);
标签: c# .net json json.net deserialization