我正在尝试从battle.net apis反序列化一个JSON对象,我无法弄清楚我将json对象解压缩到的类的格式。
在运行期间,“Races”数组始终为null。
我正在使用相同的请求从同一服务收集数据,因此不是其他请求就是问题。
我正在使用C#和RestSharp库
这是我要反序列化的json:
{
"races": [{
"id": 6,
"mask": 32,
"side": "horde",
"name": "Tauren"
}, {
"id": 5,
"mask": 16,
"side": "horde",
"name": "Undead"
}, {
"id": 2,
"mask": 2,
"side": "horde",
"name": "Orc"
}, {
"id": 7,
"mask": 64,
"side": "alliance",
"name": "Gnome"
}, {
"id": 9,
"mask": 256,
"side": "horde",
"name": "Goblin"
}, {
"id": 1,
"mask": 1,
"side": "alliance",
"name": "Human"
}, {
"id": 8,
"mask": 128,
"side": "horde",
"name": "Troll"
}, {
"id": 24,
"mask": 8388608,
"side": "neutral",
"name": "Pandaren"
}, {
"id": 11,
"mask": 1024,
"side": "alliance",
"name": "Draenei"
}, {
"id": 22,
"mask": 2097152,
"side": "alliance",
"name": "Worgen"
}, {
"id": 10,
"mask": 512,
"side": "horde",
"name": "Blood Elf"
}, {
"id": 4,
"mask": 8,
"side": "alliance",
"name": "Night Elf"
}, {
"id": 3,
"mask": 4,
"side": "alliance",
"name": "Dwarf"
}, {
"id": 25,
"mask": 16777216,
"side": "alliance",
"name": "Pandaren"
}, {
"id": 26,
"mask": 33554432,
"side": "horde",
"name": "Pandaren"
}]
}
这是我试图反序列化的类:
using System;
using System.Collections.Generic;
namespace RESTTests
{
public class Race
{
public int Id { get; set; }
public int Mask { get; set; }
public string Side { get; set; }
public string Name { get; set; }
}
public class RaceData
{
public Race[] Races { get; set; }
}
}
编辑:按要求提供更多代码
public void GetRaceData()
{
var client = CreateClient();
var request = CreateRequest("wow/data/character/classes");
IRestResponse<RaceData> responseDe = client.Execute<RaceData>(request);
RaceData race = responseDe.Data;
//at this point "races" in the race object is null and races in the response.Data object are also null
}
private RestRequest CreateRequest(String segement)
{
var request = new RestRequest(segement, Method.GET);
request.AddParameter("locale", _locale);
request.AddParameter("apikey", _apiKey);
return request;
}
private RestClient CreateClient()
{
var client = new RestClient("https://us.api.battle.net/");
return client;
}
答案 0 :(得分:2)
您可以尝试使用Newtonsoft.Json
作为示例:
string json = "load your json here as a string";
Race race = JsonConvert.DeserializeObject<Race>(json);
我认为RestSharp lib已经将Json.NET作为依赖项引用,因此,您可以从那里使用它。
答案 1 :(得分:2)
你有这门课:
public class Race
{
public int id { get; set; }
public int mask { get; set; }
public string side { get; set; }
public string name { get; set; }
}
public class RootObject
{
public List<Race> races { get; set; }
}
你总是可以使用json2csharp.com来获取针对json生成的c#类。