简体   繁体   English

如何使用Json(C#)序列化对象而忽略某些属性

[英]How to use Json (C#) to serialize an object ignoring certain properties

This should be easy, but after a day of experiments I more confused. 这应该很容易,但是经过一天的实验,我更加困惑了。 This would be so useful in test scenarios Basically I want to easily compare a object created in a test against a what I would expect, but ignoring insignificant properties. 这在测试场景中将非常有用。基本上,我想轻松地将测试中创建的对象与期望的对象进行比较,但忽略无关紧要的属性。 The object is The WPF App and I am refactoring the crucial initialization code, so The scenario would be: 该对象是WPF应用程序,我正在重构关键的初始化代码,因此该场景将是:

  • I want to make a Json copy of the object initialized in the old way (without any unimportant properties) as a json string and saved to a "gold" file 我想将以旧方式初始化的对象的Json副本(没有任何不重要的属性)作为json字符串并保存到“ gold”文件中
  • Run The Test - initialising the object the new way 运行测试-以新方式初始化对象
  • Serialise the new object to json string - and to file without the unimportant properties 将新对象序列化为json字符串-并在没有不重要属性的情况下进行文件化
  • Load the gold file -> string 加载黄金文件->字符串

  • Compare the two strings 比较两个字符串

  • voila

Essentially a dictionary of top level important properties (nae - values as a string) is what I want. 本质上,我想要的是顶级重要属性(nae-值作为字符串)的字典。 I am not interested in hierarchical complexity as I can do that in the code if I need. 我对层次结构的复杂性不感兴趣,因为我可以根据需要在代码中进行操作。 Keeping it simple ... There are many Json nugets out there and the filtering is "hidden" in the JSon encapsulation. 保持简单...有许多Json nuget,并且过滤在JSon封装中是“隐藏的”。 This is such a useful idea for unit testing, but I am struggling to get a (simple) way to do this. 这对于单元测试来说是一个非常有用的想法,但是我正在努力寻求一种(简单的)方法来做到这一点。 I don't wan't to use attributes in main class - as this is just for a specific test. 我不要在主类中使用属​​性-因为这仅用于特定测试。

I have looked at many posts and tried various ideas, but it aint getting there. 我看过很多文章并尝试了各种想法,但是并没有实现。 Please help if you can thanks 如果可以,请帮助

Terry 特里

You can do this by using newtonsoft Json.net : https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm 您可以使用newtonsoft Json.net做到这一点: https ://www.newtonsoft.com/json/help/html/SerializationAttributes.htm

You just have to not set the JsonPropertyAttribute 您只需要设置JsonPropertyAttribute

[JsonObject(MemberSerialization.OptIn)]
public class Person
{
    // "John Smith"
    [JsonProperty]
    public string Name { get; set; }

    // "2000-12-15T22:11:03"
    [JsonProperty]
    public DateTime BirthDate { get; set; }

    // new Date(976918263055)
    [JsonProperty]
    public DateTime LastModified { get; set; }

    // not serialized because mode is opt-in
    public string Department { get; set; }
}

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

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