2013-03-16 13 views
10

Sto usando JSON.NET come serializzatore principale.Perché quando deserializzo con JSON.NET ignora il mio valore predefinito?

Questo è il mio modello, guarda che ho impostato alcuni JSONProperties e un DefaultValue.

public class AssignmentContentItem 
{ 
    [JsonProperty("Id")] 
    public string Id { get; set; } 
    [JsonProperty("Qty")] 
    [DefaultValue(1)] 
    public int Quantity { get; set; } 
} 

Quando ho serializzare un List<AssignmentContentItem>, che facendo un buon lavoro:

private static JsonSerializerSettings s = new JsonSerializerSettings 
{ 
    DefaultValueHandling = DefaultValueHandling.Ignore, 
    NullValueHandling = NullValueHandling.Ignore 
}; 

USCITA:

[{"Id":"Q0"},{"Id":"Q4"},{"Id":"Q7"}] 

Ma quando mi piacerebbe deserializzare questo jsonContent, la proprietà è Qty sempre 0 e non è impostato sul valore predefinito. Voglio dire, quando ho deserializzare che jsonContent, come DefaultValue per la quantità dovrebbe essere uno invece di 0.

public static List<AssignmentContentItem> DeserializeAssignmentContent(string jsonContent) 
{ 
    return JsonConvert.DeserializeObject<List<AssignmentContentItem>>(jsonContent, s); 
} 

Cosa devo fare

+0

Hai provato l'impostazione DefaultValueHandling.Populate? – Slugart

risposta

12

L'attributo DefaultValue non imposta il valore della proprietà. Vedere questa domanda: .NET DefaultValue attribute

Quello che potrebbe essere meglio fare sta impostando il valore nel costruttore:

public class AssignmentContentItem 
{ 
    [JsonProperty("Id")] 
    public string Id { get; set; } 
    [JsonProperty("Qty")] 
    public int Quantity { get; set; } 

    public AssignmentContentItem() 
    { 
     this.Quantity = 1; 
    } 
} 

Dove questa linea:

AssignmentContentItem item = 
    JsonConvert.DeserializeObject<AssignmentContentItem>("{\"Id\":\"Q0\"}"); 

Risultati in un AssignmentContentItem con la sua Quantity set a 1.

6

È possibile utilizzare l'impostazione DefaultValueHandling.Populate in modo che Json.Net popolerà l'oggetto creato con il valore predefinito.

public static List<AssignmentContentItem> DeserializeAssignmentContent(string jsonContent) 
{ 
    return JsonConvert.DeserializeObject<List<AssignmentContentItem>>(jsonContent, new JsonSerializerSettings 
    { 
      DefaultValueHandling = DefaultValueHandling.Populate, 
      NullValueHandling = NullValueHandling.Ignore 
    }); 
} 

http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DefaultValueHandling.htm

Problemi correlati