2015-10-15 180 views
2

现有对象我使用填充类Json.Net这样的:上面填充使用JSON

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

你提前知道哪些属性将被填充在第一和第二次的时间? – mason

+0

是的。前3个属性将首先填充,然后是最后3个。 – obautista

+2

因此听起来像手动硬编码那样会很简单。像'MyObject.mail = NewObject.mail; MyObject.mail = NewObject.uid; MyObject.userPassword = NewObject.userPassword;' – mason

回答

2

是的,你可以使用JsonConvert.PopulateObject()填写性质从第二JSON字符串现有的对象上。

下面是一个例子:

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

输出:

CID: 13579 
jsonrpc: something 
id: 24680 
mail: [email protected], [email protected] 
uid: 87654, 192834 
userPassword: superSecret, letMeInNow! 

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