【问题标题】:How to JsonConvert.SerializeObject after object cast? [duplicate]对象转换后如何 JsonConvert.SerializeObject? [复制]
【发布时间】:2018-01-23 21:32:49
【问题描述】:

对象转换后如何 JsonConvert.SerializeObject?

我有两个类似这个例子的类,我希望我的序列化 json 不包含“Id”字段。

public class Person : Description
{
    public int Id { get; set; }
}
public class Description
{
    public string Name { get; set; }
}


Person person = new Person() { Id = 1, Name = "Bill" };
Description description = person;
string jsonDescription = JsonConvert.SerializeObject(description);
Console.WriteLine(jsonDescription);
// {"Id":1,"Name":"Bill"}

我已经尝试了几种方法,例如使用“as”进行强制转换或使用 .Cast() 进行强制转换,但还没有成功。

感谢您的建议。

【问题讨论】:

    标签: c# json casting


    【解决方案1】:

    只需使用JsonIgnore 属性。

    public class Person : Description
    {
        [JsonIgnore]
        public int Id { get; set; }
    }
    

    【讨论】:

    • 这对我有用。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 2020-05-02
    • 2018-11-24
    • 2015-10-02
    • 2021-09-08
    相关资源
    最近更新 更多