facebook-csharp-sdk / simple-json

JSON library for .NET 2.0+/SL4+/WP7/WindowsStore with optional support for dynamic and DataContract
MIT License
380 stars 143 forks source link

Dictionaries are not serialized properly #80

Open ygoe opened 6 years ago

ygoe commented 6 years ago

Deserialize this JSON

{
  "profiles": {
    "production": {
      "host": "localhost",
      "username": "root"
    }
  }
}

into this class

class File
{
    public Dictionary<string, Profile> profiles { get; set; }
}
class Profile
{
    public string host { get; set; }
    public string username { get; set; }
}

and you get a dictionary with one key of "production" and its value containing "localhost" and "root".

Serialize it back to JSON and (after some formatting, see #79) you get

{
  "profiles": [
    {
      "Key": "production",
      "Value": {
        "host": "localhost",
        "username": "root"
      }
    }
  ]
}

Seems like SimpleJson didn't recognise the Dictionary and treated it as an IEnumerable<KeyValuePair<string, Profile>> instead, serializing its properties "Key" and "Value".

The problem lies in line 1015 in the method SimpleJson.SerializeValue:

IDictionary<string, object> dict = value as IDictionary<string, object>;

That won't find dictionaries of any other value type than object, which is a useless type because you can't do anything with it. In my case, that's Profile instead of object.