繁体   English   中英

使用JSON填充现有对象

[英]Populate an existing object with JSON

我使用Json.Net填充类,如下所示:

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

上面的结果JSON字符串填充了我的Account类中的几个属性。 我后来有一个新的JSON字符串,并希望使用其余属性填充相同的Account类。 这可能使用JSON.NET或JsonConvert方法吗? 我基本上想要添加/添加到我在上面的代码行中填充的帐户对象。

我的课:

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

是的,您可以使用JsonConvert.PopulateObject()从第二个JSON字符串填充现有对象的属性。

这是一个例子:

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

输出:

CID: 13579
jsonrpc: something
id: 24680
mail: abc@example.com, def@example.org
uid: 87654, 192834
userPassword: superSecret, letMeInNow!

小提琴: https//dotnetfiddle.net/621bfV

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM