Populate an existing object with JSON

obautista picture obautista · Oct 15, 2015 · Viewed 8.5k times · Source

I populate a class using Json.Net like this:

var account = JsonConvert.DeserializeObject<Account>(result.ToString());

The result JSON string above populates a couple of properties in my Account class. I later have a new JSON string and want to populate the same Account class with the remaining properties. Is this possible using JSON.NET or a JsonConvert method? I basically want to append/add to the account object I've populated in the line of code above.

My class:

public class Account
{
    public string CID { get; set; }            
    public string jsonrpc { get; set; }
    public string id { get; set; }
    public List<string> mail { get; set; }
    public List<string> uid { get; set; }
    public List<string> userPassword { get; set; }            
}

Answer

Brian Rogers picture Brian Rogers · Oct 16, 2015

Yes, you can use JsonConvert.PopulateObject() to fill in properties on an existing object from a second JSON string.

Here is an example:

string json1 = @"
{
    ""CID"": ""13579"",
    ""jsonrpc"": ""something"",
    ""id"": ""24680""
}";

Account account = JsonConvert.DeserializeObject<Account>(json1);

string json2 = @"
{
    ""mail"": [ ""[email protected]"", ""[email protected]"" ],
    ""uid"": [ ""87654"", ""192834"" ],
    ""userPassword"": [ ""superSecret"", ""letMeInNow!"" ]
}";

JsonConvert.PopulateObject(json2, account);

Console.WriteLine("CID: " + account.CID);
Console.WriteLine("jsonrpc: " + account.jsonrpc);
Console.WriteLine("id: " + account.id);
Console.WriteLine("mail: " + string.Join(", ", account.mail));
Console.WriteLine("uid: " + string.Join(", ", account.uid));
Console.WriteLine("userPassword: " + string.Join(", ", account.userPassword));

Output:

CID: 13579
jsonrpc: something
id: 24680
mail: [email protected], [email protected]
uid: 87654, 192834
userPassword: superSecret, letMeInNow!

Fiddle: https://dotnetfiddle.net/621bfV