Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize nested, complex json object to just a string c#

Tags:

json

c#

json.net

I have JSON which looks like:

{
  "name": "foo",
  "settings": {
    "setting1": true,
    "setting2": 1
  }
}  

I know how to use json2csharp.com to create the C# classes to deserialize this. They looks like:

public class Settings
{
    public bool settings1 { get; set; }
    public int settings2 { get; set; }
}

public class RootObject
{
    public string name { get; set; }
    public Settings settings { get; set; }
}

but what I want is to simply deserialize it into

public class RootObject
{
    public string name { get; set; }
    public string settings { get; set; }
}

i.e., all of the "setting" JSON just needs to be saved as a string--the structure of that JSON is not consistent. How can that be done? Thanks!

like image 544
John Avatar asked Nov 24 '25 05:11

John


1 Answers

You could use a JToken to capture your unknown settings during deserialization, then use a second property to allow you to access that JSON as a string if you need to.

Set up your class like this:

public class RootObject
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonIgnore]
    public string Settings
    {
        get { return SettingsToken != null ? SettingsToken.ToString(Formatting.None) : null; }
        set { SettingsToken = value != null ? JToken.Parse(value) : JValue.CreateNull(); }
    }

    [JsonProperty("settings")]
    private JToken SettingsToken { get; set; }
}

Then deserialize as usual:

var root = JsonConvert.DeserializeObject<RootObject>(json);

The Settings property will contain the settings part of the JSON as a string. If you reserialize the object back to JSON then the settings will retain whatever structure it had before.

You can also change the Settings property to some other JSON string, as long as it is well-formed. (If it isn't, then an exception will be thrown immediately.)

Here is a round-trip demo: https://dotnetfiddle.net/thiaWk

like image 79
Brian Rogers Avatar answered Nov 25 '25 20:11

Brian Rogers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!