2012-10-05 3 views
15

私は自分のウェブサイトにJson.Netを使用しています。シリアライザはデフォルトでcamelcaseのプロパティ名をシリアル化します。私は手動で割り当てるプロパティ名を変更したくありません。私は、次のコードを持っている:Json.NetにPropertyNameが明示的に設定されていない場合のみCamelCase?

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); 
} 

Experimentからの出力は次のとおりです。ただし

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

、私は出力になりたい:

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

はこれが実現することは可能ですか?

+0

'CamelCasePropertyNamesContractResolver'を使用してのみ、' JsonProperty'を使いません。 –

+0

@ L.B私がJsonPropertyのみを使用する場合、デフォルト命名はPascalCaseになりますので、JSONでは 'normalProperty'が' NormalProperty'になります。 – Oliver

+0

Oliverいいえ、これはJsonPropertyのものとまったく同じにシリアライズされています。 –

答えて

18

あなたは、このようなCamelCasePropertyNamesContractResolverクラスオーバーライドすることができます。

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

if(res.PropertyName!= null && attr.PropertyName!= null) 'これを行うと、名前のないフィールドに' JsonProperty'属性を設定して、通常のラクダのケーシングで処理します。 '[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]'のようなものを設定したい場合に便利です。 –

関連する問題