0

I have a composite model

public class Composite
{
    public SubType1 Property1 {get;set}
    public SubType2 Property2 {get;set}
    public IDictionary<string, object> Property3 {get;set}
}

When WEB API hydrates it, Property3 contains ExpandoObject. Then this composite type goes into Stage1 processing in the end of which it ends us as JSON in DB. In the Stage2, it is being pulled from DB and serialized like this

Composite comp = JsonConvert.DeserializeObject<Composite>(json);

At this point comp.Property3 is of type Dictionary<string, object>

Is there a way to tell JsonConvert, which implementation of IDictionary<string, object> for that property you need in each particular case? Jumping ahead I can say, I am not looking to get ExpandoObject back but rather have ability to tell that this specific property should be of some specific type.

T.S.
  • 18,195
  • 11
  • 58
  • 78
  • You either need to serialize and deserialize with the [`TypeNameHandling`](https://www.newtonsoft.com/json/help/html/SerializationSettings.htm#TypeNameHandling) setting set to `Auto` to automatically embed the type information into the JSON, or else you need to use a custom `JsonConverter` when you deserialize to recognize some discriminator within the JSON to create the correct type. See [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/10263) for an example. – Brian Rogers Sep 09 '19 at 17:22

1 Answers1

0

Make an object of the expected json return for the properties you want. Then use JavaScriptSerializer.ConvertToType<yourobject>. This will attempt to convert the json response to your custom object.

*you can leave out unneeded/unwanted items from your object. So if the json return is complicated, only create the objects you need. You will have to structure the custom object with sub objects if the json return dictates it.

For instance

{ dogs:[
 dog:{
  hair:yes,
  legs:[
   {FLleg:yes,
   FRleg:yes,
   RLleg:no,
   RRleg:no}
   ]
  }
dog:{
  hair:no,
  legs:[
   {FLleg:yes,
   FRleg:yes,
   RLleg:yes,
   RRleg:yes}
   ]
  }
]
}

You will need a dog object that has properties of bool, hair and array of legs.

T.S.
  • 18,195
  • 11
  • 58
  • 78
Bulsatar
  • 45
  • 7