Web API - JSON将属性序列化为字符串数组

时间:2014-09-10 12:18:47

标签: json serialization json.net asp.net-web-api

我有一个班级

public class Person
    { 
      public string Name { get; set; }
      public string LastName { get; set; }
      public int Age { get; set; }
    }

我想将其序列化为:

  

{" Person":" [John,Smith,13]" }

而不是

  

{" Name":" John"," LastName":" Smith"," Age":13 }

是否可以在不编写自定义序列化程序的情况下实现此目的?如果没有,我如何仅将自定义序列化程序应用于特定类?

1 个答案:

答案 0 :(得分:4)

由于序列化Person实例时想要获得的json字符串不是标准字符串,因此您需要编写自定义转换器并使用它来装饰您的类。一种方法是这样做。编写继承自JsonConverter

的类
public class CustomConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value == null) return;

        writer.WriteStartObject();
        writer.WritePropertyName(value.GetType().Name);

        writer.WriteStartArray();

        var properties = value.GetType().GetProperties();

        foreach (var property in properties)
            writer.WriteValue(value.GetType().GetProperty(property.Name).GetValue(value));

        writer.WriteEndArray();
        writer.WriteEndObject();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof (Person);
    }
}

使用JsonConverter属性装饰您的课程:

[JsonConverter(typeof(CustomConverter))]
public class Person
{
    public string Name { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

现在假设您使用以下代码:

var person = new Person
{
    Name = "John",
    LastName = "Smith",
    Age = 13
};

var json = JsonConvert.SerializeObject(person, Formatting.Indented);

json变量将具有此值:

{
    "Person": [
        "John",
        "Smith",
        13
    ]
}

演示here