2

I have an object like this:

public class Context
{
    public Dictionary<string, object> Arguments { get; set; }
}

I serialize it using this method:

private static string Serialize(object obj)
{
    return JsonConvert.SerializeObject(obj, new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.All
    });
}

I deserialize it like this:

public Context DesirializeContext
{
    get
    {
        return JsonConvert.DeserializeObject<EventContext>(Context, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All
        });
    }
}

The problem is that when I try to deserialize it, the values in the dictionary don't have the correct type.

For example, if I have {"key1", 1} and {"key2", objectb}, after deserialization, the types of the values will be Int64 and Newtonsoft.Json.Linq.JArray.

Now I know I can use the below code to cast a value to a target object (my target type in this case is a DataTable)

(DataTable)JsonConvert.DeserializeObject(Arguments["SubstituteData"].ToString(), typeof(DataTable));

But is there anyway to automatically cast the values in the dictionary to their original type when desirializing? This would make things much easier.

Vin Shahrdar
  • 1,151
  • 1
  • 12
  • 30
  • Unless it is desrializing to a strongly typed object the returned object defaults to the internals provided by Json.Net. – Nkosi Aug 24 '17 at 18:10
  • Take a look at this https://www.newtonsoft.com/json/help/html/DeserializeDataSet.htm it is for a dataset however. – Nkosi Aug 24 '17 at 18:13
  • @Nkosi, so what is the optimal solution here? deserialize again and explicitly cast to a type whenever I want to retrieve a value from this dictionary? – Vin Shahrdar Aug 24 '17 at 18:17
  • Really cant see any other way at the moment. For me this just looks like a design issue. I was advise reviewing the initial design choices. – Nkosi Aug 24 '17 at 18:20
  • I think this question is related: https://stackoverflow.com/questions/35592256/json-net-how-do-i-include-type-name-handling-for-primitive-c-sharp-types-that – StriplingWarrior Aug 24 '17 at 18:32

0 Answers0