Hello. I apologize for the possibly stupid question, but I can’t figure out how to properly jamp the following json into some kind of model. Those. the Result object may be different depending on the query. Suppose there is a Response model:

public class Response { public string Version {get;set;} public int StatusCode {get;set;} public object Result {get;set;} } 

And there is a response:

 { "Version":"1.2.3", "StatusCode":200, "Result": { "Id":42, "QuestionText":"This is a test question", "QuestionImageUrl": "http://www.blah.com/test.png" } } 

If you perform this operation, then Result will be of type object, is it possible to somehow mate it into the desired model?

 var result = JsonConvert.DeserializeObject<Response>(json); 
  • 2
    And how can you find out exactly what type of result will come? Or just looking at the result itself? - VladD
  • And if so: public dynamic Result {get;set;} ..? but, of course, I agree with VladD, the type of result is desirable to know. - Anton Komyshan
  • Does the result always have the same structure? - eastwing
  • one
    when working with json you can always map it to a Dictionary, in this case you can also use JObject - Grundy

1 answer 1

In .NET, working with JSON is most often not based on built-in tools, but on the Newtonsoft.Json package.

In it, of course, this case is provided. By creating an instance of Newtonsoft.Json.JsonSerializer, you can specify parameters such as TypeNameHandling and TypeNameAssemblyFormat that allow you to customize the serialization of information about the type of object being serialized. The library will do the rest.

If you know what type will come to you, even at the compilation stage, you can simply use the generic method Deserialize without prior configuration.