Ryan MacPhee
Ryan MacPhee

Reputation: 73

How would I deserialize a JSON String when i dont require every value?

Scenario

I am creating a small stateless API type thing which pulls information from a single API, takes only the relevant data, Takes the data and uses it as a search term within the second API. From here I then want to take only relevant information and return it to the user.

The Issue

The JSON is returned with many values within a single array(most of which are not required) and from my understanding, I need to deserialize the string into individual objects so I can then do a .Count to find out the number of cards which have been returned.

JSON String

The JSON String is large so I will just leave this link in case anyone is interested. https://api.pokemontcg.io/v1/cards?name=POKEMONNAME

Values I am looking for

What I have already Tried

var obj = JsonConvert.DeserializeObject<PokemonTCGApi>(data); 

List<PokemonTCGApi> obj = JsonConvert.DeserializeObject<List<PokemonTCGApi>>(data);

PokemonTCGApi[] objList = new JavaScriptSerializer().Deserialize<Order[]>(orderJson);

var obj = JsonConvert.DeserializeObject(data);

List<JSONClass.Card> list = JsonConvert.DeserializeObject<List<JSONClass.Card>>(data);


PokeTCG Model

    public class PokemonTCGApi
    {
        public string cardName { get; set; }
        public string imageUrl { get; set; }
        public string Types { get; set; }
        public string Artist { get; set; }

        public PokemonTCGApi(string cardName, string imageUrl, string types, string artist)
        {
            this.cardName = cardName;
            this.imageUrl = imageUrl;
            Types = types;
            Artist = artist;
        }

        public PokemonTCGApi(string cardName)
        {
            this.cardName = cardName;
        }
    }

Upvotes: 1

Views: 130

Answers (2)

Mark Cilia Vincenti
Mark Cilia Vincenti

Reputation: 1614

You can deserialize to a List and take only the relevant bits from there.

var myData = JsonConvert.DeserializeObject<List<ExpandoObject>>(jsonString);

Upvotes: 0

Devnarayan Nagar
Devnarayan Nagar

Reputation: 41

If you don't require every value from json string then create to class object what ever response you needed from deserialize, and do like that.

 var data = JsonConvert.DeserializeObject<List<EmployeeViewModel>>(json_array_string);

var data1 = JsonConvert.DeserializeObject<EmployeeViewModel>(json_string);

Upvotes: 1

Related Questions