自定义对象序列化

时间:2018-02-22 11:43:12

标签: c# json serialization json.net

有没有办法改变json中对象的序列化方式?例如,以下对象:

class PersonName {
  public string Name { get; set; }
}

var obj = new { 
    pName = new PersonName { 
        Name = "Andrew"
    }
}

序列化为{"pName": { "name": "Andrew" }}

但有没有办法将其序列化为{"pName": "Andrew"}

2 个答案:

答案 0 :(得分:1)

这应该有效:

class PersonName 
{
    [JsonProperty(PropertyName = "pName")]
    public string Name { get; set; }
}
var obj = new  PersonName { Name = "Andrew" }

答案 1 :(得分:0)

所以最后我设法得到了这个答案。

需要自定义转换器:

public class PersonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var person = value as PersonName;
        if (person == null)
        {
            return;
        }
        serializer.Serialize(writer, person.Name);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var constructorInfo = objectType.GetTypeInfo().GetConstructors(BindingFlags.Public | BindingFlags.Instance).Single();
        var parameterInfo = constructorInfo.GetParameters().Single();
        var parameterType = parameterInfo.ParameterType;

        var value = serializer.Deserialize(reader, parameterType);
        return Activator.CreateInstance(objectType, new[] { value });
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(PersonName).GetTypeInfo().IsAssignableFrom(objectType);
    }
}

可以这样使用:

[JsonConverter(typeof(PersonConverter))]
public class PersonName
{
    public PersonName(string name)
    {
        Name = name;
    }

    public string Name { get; set; }
}