【问题标题】:How to ignore a property from serialization but keep in for deserialization using json.net in c# [duplicate]如何从序列化中忽略一个属性,但在 c# 中使用 json.net 进行反序列化 [重复]
【发布时间】:2019-11-29 12:24:25
【问题描述】:

如何忽略序列化中的属性,但在 c# 中使用 json.net 进行反序列化。

例子:

public class Foo
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("contentType")]
    public object ContentType { get; set; }

    [JsonProperty("content")]
    public object Content { get; set; }

    [JsonIgnore]
    public Relationship RelationshipContent { get; set; }

    [JsonIgnore]
    public Domains DomainContent { get; set; }

}

在上面的代码中,我需要根据 PartType 属性值的值将“内容”反序列化为属性“RelationshipContent”和“DomainContent”。

你能帮我在 C# 中使用 Newtonsoft.Json 吗?

【问题讨论】:

    标签: c# asp.net-core json.net json-deserialization


    【解决方案1】:

    您能否为Content 的“集合”提供一种方法,并将数据处理到正确的位置。

    public class Foo
    {
        [JsonProperty("id")]
        public int Id { get; set; }
    
        [JsonProperty("contentType")]
        public object ContentType { get; set; }
    
        [JsonProperty("content")]
        public object Content { get; set {
                //do something here with `value` e.g.
                RelationshipContent = value; //change as required
                DomainContent = value; //change as required
            }
        }
    
        [JsonIgnore]
        public Relationship RelationshipContent { get; set; }
    
        [JsonIgnore]
        public Domains DomainContent { get; set; }
    
    }
    

    【讨论】:

    • 感谢您帮助我解决了我的问题。
    • 很高兴能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2020-06-08
    • 2016-05-31
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多