在c#中反序列化JSON时,我们能否同时为其他属性生成属性值?

时间:2019-01-21 11:33:20

标签: c# json json-deserialization

我有一个Artifact类,用于反序列化使用JsonConvert.DeserializeObject()处理的JSON。

要解决的问题是,我需要将模型中不属于JSON的属性值设置为JSON中存在的其他两个属性的组合。

public class Artefact : RealmObject
    {
        [PrimaryKey]
        public string Key { get; set; }
        [JsonProperty(PropertyName = "id")]
        public int ProductId { get; set; }
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }
        [JsonProperty(PropertyName = "instructors")]
        public IList<Instructors> Instructors { get; }
        [JsonProperty(PropertyName = "startAt")]
        public string StartAt { get; set; }
        [JsonProperty(PropertyName = "endAt")]
        public string EndAt { get; set; }
        [JsonProperty(PropertyName = "actualStartAt")]
        public string ActualStartAt { get; set; }
        [JsonProperty(PropertyName = "actualEndAt")]
        public string ActualEndAt { get; set; }
        [JsonProperty(PropertyName = "status")]
        public string APIStatus { get; set; }
        [JsonProperty(PropertyName = "assignmentNumber")]
        public int AssignmentNumber { get; set; } = -1;
    }

List<Artefact> artefacts = JsonConvert.DeserializeObject<List<Artefact>>(data, _settings);

在反序列化作为API响应获得的JSON字符串的“数据”时,我希望将Key的值设置为ProductId.ToString() + AssignmentNumber.ToString()

1 个答案:

答案 0 :(得分:0)

您可以像这样在类中添加属性:

    [JsonIgnore]
    public string MyProp { get { return this.ProductId.ToString() + this.AssignmentNumber.ToString(); } }