skip to Main Content

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.

3

Answers


  1. class MyDate
    {
        public int year, month, day;
    }
    Make sure variable should be public
    
    
    
     string str = "{'firstName':'Markoff','lastName':'Chaney','dateOfBirth':{'year':'1901','month':'4','day':'30'}}";
                dynamic data = JsonConvert.DeserializeObject(str);
                if (data.dateOfBirth != null)
                {
                    string strJson = JsonConvert.SerializeObject(data.dateOfBirth);
                    MyDate myDate = JsonConvert.DeserializeObject<MyDate>(strJson);
                }
    
    Login or Signup to reply.
  2. 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; }
    }
    
    Login or Signup to reply.
  3. You can use SelectToken

     var result = JObject.Parse(jsonStr).SelectToken("dateOfBirth").ToObject<MyDate>();
    

    You need to make your class properties to public

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search