需要帮助将JSON转换为C#对象

时间:2015-06-15 12:43:38

标签: c# asp.net json object serialization

我目前正在尝试将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
    }

目前,我可以访问Event的Type,Timestamp,ItemID和参与者ID。但由于某种原因,我无法访问类中的类,例如Event_Position或Players类始终为null。

代码生成对象

    public List<Timeline_RootObject> json_timeline = new List<Timeline_RootObject>();
    json_timeline.Add(JsonConvert.DeserializeObject<Timeline_RootObject>(json));

如果有人能指导我完成这个小障碍,我会非常感激!

1 个答案:

答案 0 :(得分:1)

此属性:

public Participants players { get; set; }

与JSON字符串中的键participantFrames不对应。您必须更改属性名称,或将属性[JsonProperty("participantFrames")]添加到其中。

此外,目前尚未使用类Event_Position,也未在JSON中看到任何事件。