在C#中将JSON数组反序列化为Object

时间:2017-08-26 13:53:27

标签: c# html json api serialization

我对C#(以前使用HTML / JS / Angular的经验)非常陌生,而且我正在使用我正在使用的API重新反序列化JSON的问题。

{  
   "titles":[  
  {  
     "lastUnlock":"2016-12-28T16:34:36.0390000Z",
     "titleId":566278,
     "serviceConfigId":"6ee10100-671e-4fc4-8cf1-91700008a406",
     "titleType":"DGame",
     "platform":"Durango",
     "name":"Game1",
     "earnedAchievements":4,
     "currentGamerscore":60,
     "maxGamerscore":1000
  },
  {  
     "lastUnlock":"2016-08-05T13:02:18.4140000Z",
     "titleId":10027721,
     "serviceConfigId":"28dd0100-1521-414e-a1d8-f0ba009902c9",
     "titleType":"DGame",
     "platform":"Durango",
     "name":"Game2",
     "earnedAchievements":17,
     "currentGamerscore":1000,
     "maxGamerscore":1000
  },
  {  
     "lastUnlock":"2016-05-02T20:52:40.3705214Z",
     "titleId":62572131,
     "serviceConfigId":"54240100-7870-4a47-8cec-7cfd03bac663",
     "titleType":"DGame",
     "platform":"Durango",
     "name":"Game3",
     "earnedAchievements":35,
     "currentGamerscore":1000,
     "maxGamerscore":1000
  },
     ],
   "pagingInfo":{  
      "continuationToken":null,
      "totalRecords":86
   }
}

问题是我不知道如何将其反序列化为对象数组。

我创建了一个对象类:

public class Game
    {
        public string name { get; set; }
        public string gamertag { get; set; }
        public string platform { get; set; }
        public int earnedAchievements { get; set; }
        public string currentGamerscore { get; set; }
        public string maxGamerscore { get; set; }
        public string lastUnlock { get; set; }
    }

从那里我尝试使用JsonConvert.DeserializeObject(结果),但这只返回“CompleteAdmin.Controllers.AchievementsAPIController + Game”,这是不可用的。

有人能告诉我这应该如何设置吗?最终我的目标是将其传入数据库。 :)

感谢。

2 个答案:

答案 0 :(得分:2)

简单就像

在Visual Studio中右键单击解决方案并选择“管理NuGet包”,将在顶部搜索类型“newtonsoft”中打开一个菜单,选择带有黑色图标的第一个选项。并添加到您的项目。然后写下以下内容。

current_year = Time.now.year 

if !(:grad_year.nil?)
        validates :grad_year, numericality: { greater_than_or_equal_to: current_year, less_than_or_equal_to: current_year + 5 }
end

在页面加载或您想要结果的位置:

public class Games
{
    public Game[] titles { get; set; }
}

public class Game
{


    public string name { get; set; }
    public string gamertag { get; set; }
    public string platform { get; set; }
    public int earnedAchievements { get; set; }
    public string currentGamerscore { get; set; }
    public string maxGamerscore { get; set; }
    public string lastUnlock { get; set; }
}

答案 1 :(得分:0)

只需添加一个额外的类来包含Titles(或Games的集合,更能让您下定决心......)

public class Container
{
    public Game[] Titles { get; set; }
}

现在您可以轻松地反序列化:

var res = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Container>(jsonObject);

要使用此功能,请在项目中添加System.Web.Extensions的引用。

请注意,我必须从您的JSON中删除逗号才能使其生效:

 },    <------ this comma should not be there
  ],
"pagingInfo":{  
   "continuationToken":null,
   "totalRecords":86
}