将JSON C#类调用到方法中

时间:2016-08-10 22:56:12

标签: c# json json.net json-api

我有一个像这样的JSON API,

{
 "pokemon": {
 "currentPokemon": 1,
 "total": 1,
 "totalCount": 1,
 },
"collections": [
{
  "pokemonId": 2310,
  "pokemonName": "Pikachu",
  "pokemonType": "Land",
  "status": {
    "Active": "YES",
    "Holder": "ASH"
  },
  "power": {
    "Type": 10,
    "name": "Thunder"
  },

}
]
}

我有这些API的C#类

Public ClassPokemonster 
{

public class RootObject
{
 [JsonProperty("pokemon")]
 public Pokemon Pokemon { get; set; }
 [JsonProperty("collections")]
 public List<Collection> Collections { get; set; }
}
public class Pokemon
{
 [JsonProperty("currentPokemon")]
 public int CurrentPokemon { get; set; }
 [JsonProperty("total")]
 public int Total { get; set; }
 [JsonProperty("totalCount")]
 public int TotalCount { get; set; }
}
public class Collection
{
 [JsonProperty("pokemonId")]
 public int PokemonId { get; set; }
 [JsonProperty("pokemonName")]
 public string PokemonName { get; set; }
 [JsonProperty("pokemonType")]
 public string PokemonType { get; set; }
 [JsonProperty("status")]
 public Status Status { get; set; }
 [JsonProperty("power")]
public Power Power { get; set; }
}
public class Status
{
 [JsonProperty("Active")]
 public string Active { get; set; }
 [JsonProperty("Holder")]
 public string Holder { get; set; }
}
public class Power 
{
 [JsonProperty("Type")]
 public int Type { get; set; }
 [JsonProperty("name")]
 public string Name { get; set; }
}
}

我正在尝试使用此方法断言与API值匹配的值

         Driver.Instance.Navigate().GoToUrl(url);
        //WebRequest
        HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(url);
        getRequest.Method = "GET";

        var getResponse = (HttpWebResponse)getRequest.GetResponse();
        Stream newStream = getResponse.GetResponseStream();
        StreamReader sr = new StreamReader(newStream);

        //Deserialize JSON results
        var result = sr.ReadToEnd();
        Pokemonster deserializedObjects = JsonConvert.DeserializeObject<Pokemonster>(result);

我试图以这种方式断言,

  Assert.Equal("2310", deserializedObject.Collections.PokemonId.ToString());

我的断言不会获取collections类中的值,例如pokemonoId pokemonName等等!

帮我解决这个问题!

1 个答案:

答案 0 :(得分:1)

第一个问题(这可能只是你在这里如何格式化它的一个问题,但我应该提到它的完整性)是你有:

Public ClassPokemonster

但正确的语法是:

public class Pokemonster

接下来,请注意所有其他类都在内部Pokemonster中声明。这种结构称为nested type。您设计它的方式,Pokemonster类本身不包含任何属性或方法,但嵌套类Pokemonster.RootObjectPokemonster.Pokemon等确实具有属性。因此,为了正确反序列化此类型,您必须使用:

Pokemonster.RootObject deserializedObjects = 
    JsonConvert.DeserializeObject<Pokemonster.RootObject>(result);

最后,请注意,属性Pokemonster.RootObject.Collections实际上具有List<Pokemonster.Collection>类型,但List<T>没有任何名为PokemonId的属性(因此出现错误消息)。您必须访问此列表中的项目才能获取其中的任何属性,如下所示:

Assert.Equal("2310", deserializedObject.Collections[0].PokemonId.ToString());