4

Disclaimer: There are many topics on this subject, however so far I found only one on the topic of partial deserialisation thisone, which already is a couple of years old

The question: What is the easiest way in json.net, yet without much overhead, to deserialize a partial JSON string to object?

Given a JSON object:

{
    "message":"Login successful",
    "data":{
        "firstname":"John",
        "lastname":"Doe",
    }
}

and an object:

public class UserData
{
    [JsonProperty("firstname")]
    public string FirstName;

    [JsonProperty("lastname")]
    public string LastName;
}

than, there are many methods you can use. e.g. create another object that holds a variable UserData data and deserialize to that object. However, if you want to access FirstName, you'll always have to add the data (data.FirstName) which is.. not nice.

Another method (as in the post linked above) is to deserialize the object to dynamic/var, get the data part of it, serialize it and feed that string to the

dynamic obj = JsonConvert.DeserializeObject(JSONString);
UserData User = JsonConvert.DeserializeObject<Model.UserData>(JsonConvert.SerializeObject(obj["data"]));

Yes, it works well, but perhaps a bit much overhead? Another option is to use a custom JsonConverter, but that seems to be allot of code for such a simple thing.

I was hoping to use something like

[JsonProperty("data.firstname")]
public string FirstName;

or another setting, to let json.net know it should use the path data for the deserialisation of the JSON string to UserData, but I havent found such a thing in the documentation.

Any suggestions?

Jeffrey
  • 1,766
  • 2
  • 24
  • 44
  • 1
    This what you're looking for? [Can I specify a path in an attribute to map a property in my class to a child property in my JSON?](https://stackoverflow.com/q/33088462). – dbc Sep 27 '17 at 09:43
  • @dbc Thank you, didnt see that method yet; it's most certainly a nice addition to the list. However, this requires a line of code for each item in `data` to properly assign it to the appropriate variable in the object. Meaning that if there are 100 variables in data, you need 100 lines to assign each of them. *Edit:* didn't look far enough down. This actually might be the best way to do it! – Jeffrey Sep 27 '17 at 10:02
  • @dbc this works better than I expected (the fancy part that Brian Rogers has in his post). Please mark this question as duplicate, or post the link as answer so I can accept. – Jeffrey Sep 27 '17 at 10:20

0 Answers0