Search code examples
c#json.netdeserialization

How can I convert a single object of a json string into a .Net object?


I have a class like these:

class MyDate
{
    int year, month, day;
}

I want to fill an object of this class with the data from this JSON string (only from "dateOfBirth"):

{
    "firstName":"Markoff",
    "lastName":"Chaney",
    "dateOfBirth":
    {
        "year":"1901",
        "month":"4",
        "day":"30"
    }
}

I know the JsonConvert.DeserializeObject<>(jsonString)

but I am looking for a way to convert only a single object of a whole JsonString into a .Net object.

I am looking for a DeserializeObject method with a JObject as parameter.


Solution

  • you need to parse your json string, only after this you can deserialize any part you need. Your class should be fixed too.

    using Newtonsoft.Json;
    
    MyDate myDate = JObject.Parse(json)["dateOfBirth"].ToObject<MyDate>();
    
    public class MyDate
    {
        public int year { get; set; }
        public int month { get; set; }
        public int day { get; set; }
    }