2012-10-05 10 views
15

Sto usando Json.Net per il mio sito web. Voglio che il serializzatore serializzi i nomi di proprietà in camelcase per impostazione predefinita. Non voglio che cambi i nomi di proprietà che assegno manualmente. Ho il seguente codice:CamelCase solo se PropertyName non è impostato in modo esplicito in Json.Net?

public class TestClass 
{ 
    public string NormalProperty { get; set; } 

    [JsonProperty(PropertyName = "CustomName")] 
    public string ConfiguredProperty { get; set; } 
} 

public void Experiment() 
{ 
    var data = new TestClass { NormalProperty = null, 
     ConfiguredProperty = null }; 

    var result = JsonConvert.SerializeObject(data, 
     Formatting.None, 
     new JsonSerializerSettings {ContractResolver 
      = new CamelCasePropertyNamesContractResolver()} 
     ); 
    Console.Write(result); 
} 

L'uscita da Experiment è:

{"normalProperty":null,"customName":null} 

Tuttavia, voglio l'output di essere:

{"normalProperty":null,"CustomName":null} 

È questo possibile raggiungere?

+0

non usare 'CamelCasePropertyNamesContractResolver' e usare' JsonProperty' solo. –

+0

@ L.B Se utilizzo solo JsonProperty, il nome predefinito sarà PascalCase, quindi 'normalProperty' sarà invece' NormalProperty' nel JSON. – Oliver

+0

Oliver No, è serializzato esattamente come ciò che si dà in JsonProperty. –

risposta

18

è possibile ignorare la classe CamelCasePropertyNamesContractResolver in questo modo:

class CamelCase : CamelCasePropertyNamesContractResolver 
{ 
    protected override JsonProperty CreateProperty(MemberInfo member, 
     MemberSerialization memberSerialization) 
    { 
     var res = base.CreateProperty(member, memberSerialization); 

     var attrs = member 
      .GetCustomAttributes(typeof(JsonPropertyAttribute),true); 
     if (attrs.Any()) 
     { 
      var attr = (attrs[0] as JsonPropertyAttribute); 
      if (res.PropertyName != null) 
       res.PropertyName = attr.PropertyName; 
     } 

     return res; 
    } 
} 
+8

Un leggero miglioramento 'if (res.PropertyName! = Null && attr.PropertyName! = Null)' Ciò consente di impostare un attributo 'JsonProperty' su un campo senza un nome e lo mantiene comunque gestito con un normale alloggiamento del cammello. Utile se vuoi impostare qualcosa come '[JsonProperty (NullValueHandling = NullValueHandling.Ignore)]' –

Problemi correlati