2016-12-16 3 views
0

C#のプロパティ名をcamelの場合に、javascript/jsonのプロパティの名前をパスカルの場合に変更するカスタムJsonConverterを作成しようとしています。私は正しい軌道に乗っているように感じますが、私は何をする必要があるのか​​を理解することができません(そして、私は時間を過ごしています)。ViewModelカスタムJsonConverter

私はJsonProperty属性をC#プロパティに追加できますが、各プロパティではなくクラスに属性を適用したいと考えています。

public class ViewModelJsonConverter : JsonConverter 
{ 
    public override bool CanConvert(Type objectType) 
    { 
     return true; 
    } 

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
    { 
     var model = JObject.Load(reader); 
     var properties = model.Properties(); 
     foreach (var prop in properties) 
     { 
      RenameToPascalCase(prop.Name, prop.Value); 
     } 
     return model; 
    } 

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
    { 
     var model = (JObject)JToken.FromObject(value); 
     var properties = model.Properties(); 
     foreach (var prop in properties) 
     { 
      RenameToCamelCase(prop.Name, prop.Value); 
     } 
    } 


    private void RenameToCamelCase(string name, JToken value) 
    { 
     var parent = value.Parent; 
     if (parent == null) 
      throw new InvalidOperationException("The parent is missing."); 

     var newProperty = new JProperty(ToCamelCase(name), value); 
     parent.Replace(newProperty); 
    } 

    private void RenameToPascalCase(string name, JToken value) 
    { 
     var parent = value.Parent; 
     if (parent == null) 
      throw new InvalidOperationException("The parent is missing."); 

     var newProperty = new JProperty(ToPascalCase(name), value); 
     parent.Replace(newProperty); 
    } 

    //Example: propertyName 
    private string ToCamelCase(string value) 
    { 
     if (String.IsNullOrEmpty(value) || Char.IsLower(value, 0)) 
      return value; 

     return Char.ToLowerInvariant(value[0]) + value.Substring(1); 
    } 

    //Example: PropertyName 
    private string ToPascalCase(string value) 
    { 
     if (String.IsNullOrEmpty(value) || Char.IsUpper(value, 0)) 
      return value; 

     return Char.ToUpperInvariant(value[0]) + value.Substring(1); 
    } 
} 

サンプルを使用

[JsonConverter(typeof(ViewModelJsonConverter))] 
public class TestClass { 
    public string PropertyName { get; set; } 
} 

答えて

1

Json.Net 9.0.1以降を使用している場合は、[JsonObject]属性のNamingStrategyTypeパラメータを使用して必要な操作を行うことができます。

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] 
public class TestClass 
{ 
    ... 
} 

あなたはContractResolverまたはカスタムJsonConverterを必要としない。だから、他の言葉で、ちょうどあなたがこのようにケースに入れラクダになりたいクラスをマークします。

ここ

は往復のデモです:

public class Program 
{ 
    public static void Main(string[] args) 
    { 
     TestClass tc = new TestClass 
     { 
      PropertyName = "foo", 
      AnotherPropertyName = "bar" 
     }; 

     Console.WriteLine("--- Serialize ---"); 
     string json = JsonConvert.SerializeObject(tc, Formatting.Indented); 
     Console.WriteLine(json); 
     Console.WriteLine(); 

     Console.WriteLine("--- Deserialize ---"); 
     TestClass test = JsonConvert.DeserializeObject<TestClass>(json); 
     Console.WriteLine("PropertyName: " + test.PropertyName); 
     Console.WriteLine("AnotherPropertyName: " + test.AnotherPropertyName); 
    } 
} 

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] 
public class TestClass 
{ 
    public string PropertyName { get; set; } 
    public string AnotherPropertyName { get; set; } 
} 

出力:

--- Serialize --- 
{ 
    "propertyName": "foo", 
    "anotherPropertyName": "bar" 
} 

--- Deserialize --- 
PropertyName: foo 
AnotherPropertyName: bar 
0

はあなたがnewtonsoft JSONのためにこれらの契約リゾルバのいずれかを試してみました。例えばのために は:あなたがあなた自身を実装したい場合

var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; 
var json = JsonConvert.SerializeObject(obj, Formatting.Indented, jsonSerializerSettings); 

無視してください。

+0

私はこれについて知らなかったが、私は特定のクラスにそれを適用する必要があります。これは世界的な変化のようです。そうですか? – christo8989

+0

いいえ、メソッドをシリアル化またはデシリアライズする前に起こります。 –

関連する問題