2016-06-15 60 views
1

我旁边JSON:Json.NET不要序列特定的属性

"mode":"modeValue", 
"format":"formatValue", 
"options":{ 
    "page":1, 
    "size":"70", 
    "resize":"false", 
    "templating":null 
} 

但“选项”值对象可以是与当前不同,我可以有很多不同的选择。例如,它可以是

"options": { 
    "page": 2, 
    "first": "true", 
    "parent": null 
} 

我创建了一个类

public class Settings 
{ 
    [JsonProperty(PropertyName = "mode")] 
    public string Mode { get; set; } 

    [JsonProperty(PropertyName = "format")] 
    public string OutputFormat { get; set; } 

    [JsonProperty(PropertyName = "options")] 
    public string Options { get; set; } 
} 

我不想反序列化“选项”值,但将其设置为在Options属性字符串(连载)。

注意:我只会将这个类用于反序列化。

谢谢!

回答

0

您可以使用OnDeserialized属性来实现此目的。这里有一个例子:通过Temp.ToString()

+0

public class Settings { [JsonProperty(PropertyName = "mode")] public string Mode { get; set; } [JsonProperty(PropertyName = "format")] public string OutputFormat { get; set; } [JsonIgnoreAttribute] public string Options { get; private set; } [JsonProperty(PropertyName = "options")] private object Temp { get; set; } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { Options = Temp?.ToString(); } } 

“选项”反序列化到“温度”属性,然后选择“选项”中填充谢谢!这对我很有用,所以我会将其标记为“解决方案”。 你可以告诉我什么'Temp'在'Options = Temp?.ToString();'? – Pepo

+1

Temp?.ToString()是写入temp!= null的短语吗? temp.ToString():null; – Viezevingertjes

+0

@Pepo - Viezevingertjes是对的。我已经添加这只是为了安全(如果“选项”为null或未定义在JSON中) –

相关问题