使用JSON填充现有对象 [英] Populate an existing object with JSON

查看:240
本文介绍了使用JSON填充现有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Json.Net这样填充一个类:

I populate a class using Json.Net like this:

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

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

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.

我的课:

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.

这里是一个例子:

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

这篇关于使用JSON填充现有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆