I am deserializing a string to Dictionary. Here is the code for deserialization:
public T Deserialize<T>(string serialized)
{
var serializer = new DataContractSerializer(typeof(T));
StringReader reader = null;
try
{
reader = new StringReader(serialized);
using (XmlTextReader stm = new XmlTextReader(reader))
{
reader = null;
return (T)serializer.ReadObject(stm);
}
}
finally
{
if (reader != null)
{
reader.Dispose();
}
}
}
This is how I am passing the input string :
string json = @"{""key1"":""value1"",""key2"":""value2""}";
However I get an error at the line ReadObject(stm)
:
There was an error deserializing the object of type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]. Data at the root level is invalid. Line 1, position 1.
I have tried giving the input like this:
string json = "[{'key1':'value1','key2':'value2'}]";
But I am still getting the same error. What am I doing wrong?
Edit: I cannot change the Deserialize method as its a method written by my client. I am just writing the unit test for testing it.
XmlTextReader
? Moreso, you don't seem to be using it at all. – Yuval ItzchakovDataContractSerializer
is used to serialize to XML, not JSON. – Yuval Itzchakov