如何在JsonConverter中将数组转换为对象

时间:2016-11-18 14:50:09

标签: .net json.net serializer

我想使用JsonConverter将属性的类型从数组更改为对象。例如,我有一个像[{"Name":"aaa"}]这样的属性。序列化后,我想得到像{"__po":"Add",Objects:[{"Name":"aaa"}]}一样的结果。

所以我创建了一个用于自定义序列化程序的类:

public class Serializer : ISerializer
{
    public JsonSerializerSettings SerializerSettings { get; set; }

    public Serializer()
    {
        SerializerSettings = new JsonSerializerSettings();
        SerializerSettings.Converters.Add(new ParseArrayToObjectJsonConverter());
    }

    public class ParseArrayToObjectJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            if (objectType.GetTypeInfo().Name.EndsWith("Array"))
            {
                return true;
            }
            return false;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {

        }
    }
}

我看到JsonWriter有这个属性public WriteState WriteState { get; }可以返回这样的枚举:public enum WriteState { Error = 0, Closed = 1, Object = 2, Array = 3, Constructor = 4, Property = 5, Start = 6 }

WriteJson方法中,writer.WriteState的类型为WriteState.Array,但问题是我无法设置WriteState的值以便返回宾语。你有其他解决方案可以解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

我认为您误解了如何在JsonWriter中使用JsonConverter。你永远不需要弄乱作家的WriteState。它是一个只读属性,指示作者当前正在编写的内容。你不能直接改变它。相反,您应该使用编写器的WriteXxx()方法来实际写出您想要的JSON。以下是如何实现在对象中包装数组的JsonConverter

public class WrapArrayInObjectJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        // This will cause the converter to wrap ALL IEnumerables (except strings) in an object.
        return typeof(IEnumerable).IsAssignableFrom(objectType) && objectType != typeof(string);

        // If you only want to this converter to wrap specific kinds of arrays, change this
        // method accordingly.  For example, this will only wrap Foo[] or List<Foo>:
        //return typeof(IEnumerable<Foo>).IsAssignableFrom(objectType);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        IEnumerable array = (IEnumerable)value;
        writer.WriteStartObject();
        writer.WritePropertyName("__po");
        writer.WriteValue("Add");
        writer.WritePropertyName("Objects");
        writer.WriteStartArray();
        foreach (object item in array)
        {
            serializer.Serialize(writer, item);
        }
        writer.WriteEndArray();
        writer.WriteEndObject();
    }

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

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

以下是使用转换器的示例:

Foo[] array = new Foo[]
{
    new Foo { Name = "aaa" },
    new Foo { Name = "bbb" }
};

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new WrapArrayInObjectJsonConverter());

string json = JsonConvert.SerializeObject(array, settings);
Console.WriteLine(json);

输出:

{"__po":"Add","Objects":[{"Name":"aaa"},{"Name":"bbb"}]}

小提琴:https://dotnetfiddle.net/79mXF2