cashanzlo cashanzlo - 1 year ago 204
JSON Question

Call JSON C# classes into a method

I have a JSON API like this,

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


And I have the C# Classes for those API

Public ClassPokemonster

public class RootObject
public Pokemon Pokemon { get; set; }
public List<Collection> Collections { get; set; }
public class Pokemon
public int CurrentPokemon { get; set; }
public int Total { get; set; }
public int TotalCount { get; set; }
public class Collection
public int PokemonId { get; set; }
public string PokemonName { get; set; }
public string PokemonType { get; set; }
public Status Status { get; set; }
public Power Power { get; set; }
public class Status
public string Active { get; set; }
public string Holder { get; set; }
public class Power
public int Type { get; set; }
public string Name { get; set; }

And I'm trying to assert those values matching the API values using this method

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);

I'm trying to assert in this way,

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

My assert doesn't fetch the values inside the
class such as
and so on!

Help me getting through this!

Answer Source

The first issue (it's probably just an issue with how you've formatted it here, but I should mention it for completeness) is that you have:

Public ClassPokemonster

But the correct syntax is:

public class Pokemonster

Next, notice that all your other classes are declared inside the class Pokemonster. This kind of structure is called a nested type. The way you've designed it, the Pokemonster class itself contains no properties or methods, but the nested classes Pokemonster.RootObject, Pokemonster.Pokemon, etc. do have properties. So in order to correctly deserialize this type, you have to use:

Pokemonster.RootObject deserializedObjects = 

Finally, note that the property, Pokemonster.RootObject.Collections actually has the type List<Pokemonster.Collection>, but List<T> doesn't have any property named PokemonId (hence the error message). You'll have to access an item in this list to get any of it's properties, like this:

Assert.Equal("2310", deserializedObject.Collections[0].PokemonId.ToString());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download