C. Dodds
C. Dodds

Reputation: 345

Converting a JSON String to a class when the class does not use all properties provided by the JSON string

I'm trying to figure out how to parse the following JSON string

[
  {
     "id": 1,
     "name": "Johnny"
     "dob": "12/10/1986"
     "sex": "Male"
  },
  {
     "id": 2,
     "name": "Sarah"
     "dob": "3/7/1979"
     "sex": "Female"
  }
]

The class I am trying to read it into is a list of class person which only has the variables name, dob and sex. Is there a way that is as simple to do this as it is if the class also contained id and so could just be deserialized straight into the list?

i tried looking through the other similar questions although none seem to include this aspect of not requiring some the properties appearing in the JSON string.

Upvotes: 1

Views: 177

Answers (2)

Gowri Pranith Kumar
Gowri Pranith Kumar

Reputation: 1685

You can use [JsonIgnore] attribute over the attribute if you want to ignore it

Upvotes: 0

Nkosi
Nkosi

Reputation: 247008

You can still deserialize to your person class.

Assuming

public class Person {
    public string name { get; set; }
    public string dob { get; set; }
    public string sex { get; set; }
}

It will just ignore the id in the JSON when desrializing.

For example, using the Newtonsoft.Json package.

var list = JsonConvert.DeserializeObject<List<Person>>(json);

Upvotes: 7

Related Questions