0
votes

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.

2
take a look at stackoverflow.com/questions/12397733/…user5308950
what about string json = "['key1':'value1','key2':'value2']"; ?Jakub Rusilko
I'm not familiar with the library but are you sure XmlTextReader deserializes JSON?Casey
Why are you creating an XmlTextReader? Moreso, you don't seem to be using it at all.Yuval Itzchakov
Are you sure you're allowed to pass a JSON to your method? DataContractSerializer is used to serialize to XML, not JSON.Yuval Itzchakov

2 Answers

4
votes

Instead of jumping through all these hoops and using DataContractSerializer and creating custom logic to parse json, I advise you to look into Json.NET, which makes this a joy:

string json = @"{""key1"":""value1"",""key2"":""value2""}";
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

Edit:

It looks as if you're trying to pass a JSON to a method that can only parse XML strings. I advise you ask your client provider what acceptable inputs can be used.

0
votes

You could try this -

string json = @"{""key1"":""value1"",""key2"":""value2""}";
var o = new DataContractJsonSerializer(typeof(T));
var mem = new MemoryStream(UTF32Encoding.UTF8.GetBytes(new StreamReader(json.ToCharArray()));
mem.Position = 0;
var o2 = o.ReadObject(mem);

public class T
{
    public string key1 { get; set; }
    public string key2 { get; set; }
}