需要有关将 JSON 转换为 C# 对象的帮助
本文关键字:对象 帮助 转换 JSON | 更新日期: 2023-09-27 17:56:11
我目前正在尝试将 JSON 字符串转换为 C# 对象,目前在调试过程中遇到问题。下面是 JSON 和我的类的示例。
类
public class Timeline_RootObject
{
public List<Timeline_Frame> frames { get; set; }
public int frameInterval { get; set; }
}
public class Timeline_Frame
{
public Participants players { get; set; }
public IList<Event> events { get; set; }
public int timestamp { get; set; }
}
public class Participants
{
public Players player1{ get; set; }
public Players player2 { get; set; }
}
public class Event_Position
{
public int x { get; set; }
public int y { get; set; }
}
public class Player_Position
{
public int x { get; set; }
public int y { get; set; }
}
public class Players
{
public int participantId { get; set; }
public Player_Position position { get; set; }
public int currentGold { get; set; }
}
public class Event
{
public string type { get; set; }
public int timestamp { get; set; }
public int participantId { get; set; }
public int itemId { get; set; }
}
示例 JSON
{"frames": [
{
"participantFrames": {
"player1": {
"participantId": 1,
"position": {
"x": 561,
"y": 581
},
"currentGold": 475
},
{
"player2": {
"participantId": 2,
"position": {
"x": 561,
"y": 581
},
"currentGold": 475
}
},
"events": [
{
"type": "ITEM_PURCHASED",
"timestamp": 1829,
"participantId": 1,
"itemId": 1039
}
],
"timestamp": 0
},
{
"participantFrames": {
"player1": {
"participantId": 1,
"position": {
"x": 800,
"y": 681
},
"currentGold": 525
},
{
"player2": {
"participantId": 2,
"position": {
"x": 754,
"y": 642
},
"currentGold": 525
}
},
"events": [
{
"type": "ITEM_PURCHASED",
"timestamp": 45358,
"participantId": 1,
"itemId": 684
}
],
"timestamp": 60000
}
目前,我可以访问事件的类型、时间戳、项目 ID 和参与者 ID。但是由于某种原因,我无法访问类中的类,例如Event_Position或 Player 类始终为空。
代码生成对象
public List<Timeline_RootObject> json_timeline = new List<Timeline_RootObject>();
json_timeline.Add(JsonConvert.DeserializeObject<Timeline_RootObject>(json));
如果有人能帮助指导我通过这个小障碍,我将不胜感激!
此属性:
public Participants players { get; set; }
与 JSON 字符串中的键participantFrames
不对应。您必须更改属性名称,或向其添加属性[JsonProperty("participantFrames")]
。
此外,目前未使用类Event_Position
,我在 JSON 中也没有看到任何出现。