c# - 如果反序列化时 json 中不存在,则保留旧值

标签 c# .net json json.net

我有这样一个类:

public class item
{
    public string Name { get; set; }
    public string City { get; set; }
    public string Pw { get; set; }
}

我从中创建了几个存储在数据库中的对象。然后我想用来自客户端的数据以这样的 json 形式更新其中之一:

{  
   "Name":"John",
   "City":"NYC"
}

想法是使用:

item myitem = JsonConvert.DeserializeObject<item>(jsoncomingfromclient);

但是这样做 Pw 被 null 覆盖了(虽然显然我想保留原来的值)

NullValueHandling看起来是个不错的候选者,但如果该值为空,它就可以工作,在我的例子中,它完全不在 json 中。 如果 json 中缺少值,知道如何反序列化 json 并在目标对象中保留旧值吗?

最佳答案

使用JsonConvert.PopulateObject .它专为此目的而设计:

        var item = new item { Name = "my name", City = "my city", Pw = "my pw" };

        var json = @"
        {  
           ""Name"":""John"",
           ""City"":""NYC""
        }";

        JsonConvert.PopulateObject(json, item);

        Debug.Assert(item.Pw == "my pw"); // no assert
        Debug.Assert(item.Name == "John"); // no assert
        Debug.Assert(item.City == "NYC"); // no assert

关于c# - 如果反序列化时 json 中不存在,则保留旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28610993/

相关文章:

javascript - Jquery 自动完成的 JSON

c# - 使用 Protocol Buffer 制作通用反序列化器

c# - 在 C# 的 Windows 窗体中的 PictureBox 中显示 System.Windows.Media.Imaging.BitmapSource

c# - 我如何在结构中声明数组?

c# - 是否有基于 .NET 的 CSS 抽象库?

jquery - 将数组的 JSON 数组转换为 <ul> 和 <li> 元素

javascript - 使用 jQuery/Javascript 迭代 JSON

c# - Objective-C/iPhone 中的公钥加密

c# - 在 C# 中添加和更新 DataTable 列

c# - 在 .NET 中填充整数列表