将对象反序列化为另一个类型json.net的类似对象

时间:2015-03-20 10:13:09

标签: json types deserialization

我有一个与Cannot deserialize JSON array into type - Json.NET类似的问题,但我仍然遇到错误。

所以,我有3个班级:

public class Class1
{
    public string[] P2 { get; set; }
}

public class Class2
{
    public Wrapper<string>[] P2 { get; set; }
}

public class Wrapper<T>
{
    public T Value { get; set; }
}

我正在尝试将 Class 2 序列化为字符串并返回 Class 1 。 方法如下:

Class2 c2 = new Class2 
{ 
     P2 = new Wrapper<string>[] 
        {
            new Wrapper<string> { Value = "a" },
            new Wrapper<string> { Value = "a" },
        },
};

string s = JsonConvert.SerializeObject(c2);
Class1 c1 = (Class1)JsonConvert.DeserializeObject(s, typeof(Class1), new FormatConverter());

FormatConverter类定义如下:

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

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (objectType == typeof(string[]))
        {
            List<string> list = new List<string>();
            while (reader.Read())
            {
                if (reader.TokenType != JsonToken.StartObject)
                {
                    continue;
                }
                Wrapper<string> obj = (Wrapper<string>)serializer.Deserialize(reader, typeof(Wrapper<string>));
                list.Add(obj.Value);
            }
            return list.ToArray();
        }
    }

    public override bool CanConvert(Type type)
    {
        if (type == typeof(string[]))
        {
            return true;
        }
        return false;
    }
}

我缺少什么?我得到以下异常:

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll

Additional information: Unexpected end when deserializing object. Path '', line 1, position 46.

谢谢, 亚历

1 个答案:

答案 0 :(得分:0)

我自己找到了答案。方法如下:

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (type == typeof(string[]) && reader.TokenType == JsonToken.StartArray)
        {
            //remove converter not to trigger a recursive call
            var converter = serializer.Converters[0];
            serializer.Converters.RemoveAt(0);

            //deserialization into correct type
            Wrapper<string>[] obj = (Wrapper<string>[])serializer.Deserialize(reader, typeof(Wrapper<string>[]));

            //restore converter
            serializer.Converters.Add(converter);

            if (obj != null)
            {
                return obj.Select(w => w == null ? null : w.Value).ToArray();
            }
            return reader.Value;
        }
    }