我想創建一個自定義的JsonConverter,將C#屬性名稱更改爲駝峯大小寫和javascript/json屬性名稱以pascal大小寫。我覺得我走在正確的軌道上,但是我很難理解我需要做什麼(而且我處於緊張狀態)。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; }
}
我不知道這一點,但我需要將它應用到一個特定的類。這看起來更像是一個全球變化。是對的嗎? – christo8989
不,它發生在您調用序列化或反序列化方法之前。 –