CSharp · Console
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = @"
{
""name"": ""foo"",
""settings"": {
""setting1"": true,
""setting2"": 1
}
}";
Console.WriteLine("--- deserialized from JSON ---");
var root = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine("name = " + root.Name);
Console.WriteLine("settings = " + root.Settings);
Console.WriteLine();
Console.WriteLine("--- reserialized to JSON ---");
Console.WriteLine(JsonConvert.SerializeObject(root, Formatting.Indented));
Console.WriteLine();
Console.WriteLine("--- reserialized with changed settings ---");
root.Settings = @"{ ""setting3"": ""yes"" }";
Console.WriteLine(JsonConvert.SerializeObject(root, Formatting.Indented));
}
}
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; }
}