0

Usually we deserialize using JSON.NET by this code

JsonConvert.DeserializeObject<CLASS TYPE> (text, settings);

Imagine, that we have such JSON request:

{
  "command" : "register_user",
  "params" : {
    "@c" : "register_params",
    "name" : "sdfsd",
    "email" : "sdfsd@ddkdk",
    "password" : "JDFffJJJd"
  }
}

How could we automatically detect that we need deserialize "name", "email" and "password" fields into one register_params object using JSON.NET?

Maxim Korobov
  • 2,574
  • 1
  • 26
  • 44
  • 1
    This (http://stackoverflow.com/questions/9490345/json-net-change-type-field-to-another-name) appears related as it looks like you're using @c like JSON.NET normally uses $type. – JamieSee Jul 03 '12 at 15:49
  • Could you please provide link to example, which is using such meta-field? I found article, which explain different way and not very helpful: http://dotnetbyexample.blogspot.com/2012/02/json-deserialization-with-jsonnet-class.html – Maxim Korobov Jul 04 '12 at 12:01
  • 2
    JSON.NET introduced a TypeNameHandling value which can be utilized in two ways; as an argument to the JsonSerializerSettings. In an attribute on the property you want it to apply to like this `[JsonProperty(TypeNameHandling = TypeNameHandling.All)]`. It works by writing a $type into the JSON output. I don't know of any specific articles, but take a look at http://james.newtonking.com/projects/json/help/SerializationSettings.html for an explanation of TypeNameHandling. – JamieSee Jul 05 '12 at 21:25

1 Answers1

0

Using the TypeName value "$type".

I've written two methods to do as such:

//T can be an interface or a derived type
public static T DeserializeObject<T>(string json) where T : class
//Uses "$type" to determine the object
public static object DeserializeObject(string json)

source: https://gist.github.com/ricjac/b84a1d550cfe469f3945

xx1xx
  • 1,834
  • 17
  • 16