c# - 使用 JSON 填充现有对象

标签 c# json json.net json-deserialization

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

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

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

我的类(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; }            
}

最佳答案

是的,您可以使用 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!

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

关于c# - 使用 JSON 填充现有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33138228/

相关文章:

c# - 将 SelectList 中的选定项保存到数据库

python - 无法输出包含重音符号的 json 编码字典(里面是 noob)

c# - 什么是比较 string.tolower 更好的选择?

c# - 无法在 VSE 2010 中打开 mvc c# 项目

javascript - 使用原生 javascript 从 json 解析 html 代码

java - 将具有不同键类型的映射序列化为 json

c# - 将 XElement 转换为不带 JSON 的 JObject - 或 - 为空元素配置 SerializeXNode

json.net - 如何将 Json.NET 中缺失的属性反序列化为默认值?

c# - 如何覆盖 newtonsoft json 中的 "Required.Always"

c# - 静态方法是否共享其局部变量以及在不同线程并发使用期间会发生什么?