0

I want to serialize Dictionary<string, object> and keep type information of object. But Json.Net not work as expected.

var d = new Dictionary<string, object>();
d["A"] = 1;
d["B"] = (Int16)2;
d["C"] = (byte)3;
d["D"] = SomeEnum.EnumValue;
d["E"] = true;
d["F"] = "string";

WriteToFile("xxx.json" JsonConvert.SerializeObject(d));

d = JsonConvert.DeserializeObject<string, object>(ReadFromFile("xxx.json"));
// d["A"] is long (Int64), expect Int32
// d["B"] is long (Int64), expect Int16
// d["C"] is long (Int64), expect byte
// d["D"] is long (Int64), expect SomeEnum.EnumValue

How to deserialize to the origin type ?

huang
  • 919
  • 11
  • 22
  • Can you add what's your expected result ? – HariHaran Nov 08 '19 at 04:47
  • @HariHaran edited. – huang Nov 08 '19 at 05:17
  • `UntypedToTypedValueConverter` from [this answer](https://stackoverflow.com/a/38798114/3744182) to [JSON.net (de)serialize untyped property](https://stackoverflow.com/q/38777588/3744182) might be what you need. You would need to apply it to the dictionary values. But watch out for the security issues discussed in [TypeNameHandling caution in Newtonsoft Json](https://stackoverflow.com/q/39565954/3744182), you'll need to add an appropriate serialization binder. – dbc Nov 08 '19 at 05:29

0 Answers0