Search code examples
c#.netjson.net

Newtonsoft, deserialize and convert json string element to property in an object property


How would map an element from a json object into a property of a object that is a property on my main class.

So for example:

public ParentClass{
    public SubClass theClass {get; set;}
}

public SubClass{
    public int Id {get; set;}
    public string Name {get; set;}
}

JsonConvert.DeserializeObject<ParentClass>(jsonString);

And the json string is something like:

{
   "id":123,
   "name": "Bob"
}

So id would end up in the value of SubClass.Id.


Solution

  • Just deserialize it to SubClass like this

    var theClass  = JsonConvert.DeserializeObject<SubClass>(jsonString);
    var mainClass = new ParentClass{theClass  =theClass  }