I have some JSON that I want to deserialize into an instance of a C# class. However, the class does not have all the fields/properties matching the original JSON. I would like to be able to modify the property values in the class and then serialize it back to JSON with the remaining fields and properties from the original JSON still intact.
For example, let's say I have the following JSON:
{
"name": "david",
"age": 100,
"sex": "M",
"address": "far far away"
}
And I want to deserialize it into this class:
class MyClass
{
public string name { get; set; }
public int age { get; set; }
}
After deserializing, I set the following:
myClass.name = "John";
myClass.age = 200;
Now, I want to serialize it back to JSON and get this result:
{
"name": "John",
"age": 200,
"sex": "M",
"address": "far far away"
}
Is there a way to do this using Json.Net?
You can use Json.Net's "extension data" feature to handle this.
Add a new Dictionary<string, object> property to your class and mark it with a [JsonExtensionData] attribute. (You can make it a private property if you don't want to affect the public interface of your class.) On deserialization, this dictionary will be filled with any data that doesn't match any of the other public properties of your class. On serialization, the data in the dictionary will be written back out to the JSON as properties of the object.
class MyClass
{
public string name { get; set; }
public int age { get; set; }
[JsonExtensionData]
private Dictionary<string, object> otherStuff { get; set; }
}
Here is a demo:
class Program
{
static void Main(string[] args)
{
string json = @"
{
""name"": ""david"",
""age"": 100,
""sex"": ""M"",
""address"": ""far far away""
}";
MyClass obj = JsonConvert.DeserializeObject<MyClass>(json);
Console.WriteLine("orig name: " + obj.name);
Console.WriteLine("orig age: " + obj.age);
Console.WriteLine();
obj.name = "john";
obj.age = 200;
json = JsonConvert.SerializeObject(obj, Formatting.Indented);
Console.WriteLine(json);
}
}
Output:
orig name: david
orig age: 100
{
"name": "john",
"age": 200,
"sex": "M",
"address": "far far away"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With