I have a question similar to Cannot deserialize JSON array into type - Json.NET, but I still get errors.
So, I have 3 classes:
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; }
}
I am trying to serialize Class 2 into string and back into Class 1. Here's how:
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 class is defined below:
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;
}
}
What am I missing? I get following exception:
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.
Thanks, Alex