1

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.

Pippen
  • 13
  • 2

3 Answers3

0
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);
            }
Naresh Pansuriya
  • 2,027
  • 12
  • 15
0

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; }
}
Serge
  • 40,935
  • 4
  • 18
  • 45
0

You can use SelectToken

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

You need to make your class properties to public

huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99