2

How can I specify folding?

Here's my json:

{
    "result":
    {
        "code": "123",
        "version": "1.2.3"
    },
    "error": null
}

And here's my class I want to deserialize:

public class Info
{
    [JsonProperty("code")]
    public string Code { get; set; }

    [JsonProperty("version")]
    public string Version { get; set; }

    [JsonProperty("error")]
    public string Error { get; set; }
}

Invoking like this:

var info = JsonConvert.DeserializeObject<Info>(json);

So, is there anyway I can specify, that code and version under result section? I believe I need to use JsonSerializeSettings or something like that.

Vlad
  • 852
  • 10
  • 23
  • Similar questions: [Can I serialize nested properties to my class in one operation with Json.net?](https://stackoverflow.com/questions/30175911) and [Deserializing JSON to flattened class](https://stackoverflow.com/questions/30222921). – dbc Sep 19 '16 at 19:17

1 Answers1

3

If you are able to modify your class, then you could create a second class which contains your subproperties:

public class Info
{
    [JsonProperty("result")]
    public Result Result { get; set; }

    [JsonProperty("error")]
    public string Error { get; set; }
}

public class Result
{
    [JsonProperty("code")]
    public string Code { get; set; }

    [JsonProperty("version")]
    public string Version { get; set; }
}
Nico
  • 3,542
  • 24
  • 29
  • 1
    This doesn't do what the OP wants. They specifically want to keep their current structure, and just effectively fold the result properties into that. (In particular, this solution doesn't have anything along the lines of "folding"... you've just presented "here's the straightforward way of representing your JSON".) – Jon Skeet Sep 19 '16 at 19:04
  • Granted. I assumed that the class is changeable. I updated the answer to reflect that. – Nico Sep 19 '16 at 19:07
  • Thank you, I've implement this code. – Vlad Sep 19 '16 at 19:57