Json.Net disable JsonProperty when SerializeObject


public class Student
{
    [JsonProperty("student_name")]
    public string Name { get; set; }
}

之后,我使用 [JsonProperty("student_name")] 来反序列化第三部分 json。

如何拨打电话时获得{"Name":"test"}而不是{"student_name":"test"}

string json = JsonConvert.SerializeObject(student);

意味着如何以编程方式禁用JsonProperty

更新 2013-12-03:

编写自定义合同解析器解决问题

public class JsonCustomContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member,
        MemberSerialization memberSerialization)
    {
        var res = base.CreateProperty(member, memberSerialization);
        var attrs = member
            .GetCustomAttributes(typeof(JsonPropertyAttribute), true);
        if (attrs.Any())
        {
            if (res.PropertyName != null)
            {
                //UnderlyingName overwrite attribute name
                res.PropertyName = res.UnderlyingName;
            }
        }
        return res;
    }
}
您可以通过

定义自定义JsonConverter来实现此目的。下面是一个示例代码:

public class StudentConverter: JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Student);
    }
    public override object ReadJson(JsonReader reader, Type objectType, object   existingValue, JsonSerializer serializer)
    {
        var jObject = JObject.Load(reader);
        var target = new Student();
        serializer.Populate(jObject.CreateReader(), target);
        return target;
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var std = value as Student;
        if (std == null) return;
        writer.WriteStartObject();
        writer.WritePropertyName("Name");
        writer.WriteValue(std.Name);
        writer.WriteEndObject();
    }
}

之后,您需要用StudentConverter装饰您的Student类:

[JsonConverter(typeof(StudentConverter))]
public class Student
{
    [JsonProperty("student_name")]
    public string Name { get; set; }
}

相关内容

  • 没有找到相关文章

最新更新