按条件序列化对象

时间:2018-09-05 08:45:56

标签: c# json serialization json.net deserialization

我有以下JSON

{"id":"154298_child","design":{"id":154298,"alias":"SOME NAME","published_at":"2013-02-04T00:00:00+0400","author":[]} }

和这个

{"id":"292171_manshort","design":{"id":292171,"alias":"some name2","published_at":"2014-04-08T00:00:00+0400","author":{"nickname":"Malkia"}}}

比我反序列化他们反对

public class Data
{
    public string id { get; set; }
    public Design design { get; set; }
}
public class Design
{
    public int id { get; set; }
    public string alias { get; set; }
    public DateTime published_at { get; set; }
    [JsonConverter(typeof(SingleOrArrayConverter<Author>))]
    public List<Author> author { get; set; }
}

含转换器

class SingleOrArrayConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<T>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            return token.ToObject<List<T>>();
        }
        return new List<T> { token.ToObject<T>() };
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

问题是: 如何按条件序列化对象
if(Author.Count> 1)=>然后是json的第二个示例(对象)
if(Author.Count == 0)=>然后是json的第一个示例(用于数组)

1 个答案:

答案 0 :(得分:1)

你快到了。

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    List<Author> list = value as List<Author>;
    int count = list?.Count ?? 0;

    JToken t;

    // count > 1 ?
    if (count >= 1)
    {
        t = JToken.FromObject(list[0]);
    }
    else
    {
        t = JToken.FromObject(new List<Author>());
    }

    t.WriteTo(writer);
}

不要忘记将CanWrite设置为true

public override bool CanWrite
{
    get { return true; }
}