Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - Populate an existing object with JSON

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; }            
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"": [ ""abc@example.com"", ""def@example.org"" ],
    ""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: abc@example.com, def@example.org
uid: 87654, 192834
userPassword: superSecret, letMeInNow!

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...