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; }            
}
                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
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