当SerializeObject时,Json.Net禁用JsonProperty

时间:2013-11-28 06:42:04

标签: json json.net

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更新:

编写CustomContractResolver解决问题

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

}

1 个答案:

答案 0 :(得分:1)

您可以通过定义自定义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();
    }
}

之后,您需要使用Student

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