Search code examples
c#asp.netasp.net-mvcservicestack-text

Deserialize Json into a dynamic object with ServiceStack.Text


I am using ServiceStack.Text to deserialize json into a dynamic object.

I'm encountering an error when trying to deserialize the following json:

{
  "responseHeader":{
    "status":0,
    "QTime":3,
    "params":{
      "q":"*:*",
      "indent":"true",
      "wt":"json"}},
  "response":{"numFound":1,"start":0,"docs":[
      {
        "id":"1",
        "title":["test"],
        "_version_":1480260331707039744}]
  }}

The json above is a string and this is how I am trying to deserialize it:

DynamicJson dyn = DynamicJson.Deserialize(json);    
var response = dyn.response;

But I get an error saying: dyn does not contain a definition for 'response'


dyn does return a type of ServiceStack.DynamicJson with the following value (from debugger):

{"response_header":"{\n    \"status\":0,\n    \"QTime\":0,\n    \"params\":{\n      \"q\":\"*:*\",\n      \"size\":\"0\",\n      \"indent\":\"True\",\n      \"start\":\"0\",\n      \"wt\":\"json\",\n      \"return-fields\":\"\"}}","response":"{\"numFound\":1,\"start\":0,\"docs\":[\n      {\n        \"id\":\"1\",\n        \"title\":[\"test\"],\n        \"_version_\":1480260331707039744}]\n  }"}    ServiceStack.DynamicJson

According to the answer here: Using ServiceStack.Text to deserialize a json string to object that's how its done, but what am I doing wrong here?


Solution

  • Even though DynamicJson.Deserialize does in fact return an instance of DynamicJson, you have to declare dyn as dynamic to treat it dynamically:

    dynamic dyn = DynamicJson.Deserialize(json);    
    var response = dyn.response;
    

    According to the documentation for DynamicObject (which DynamicJson inherits from):

    In C#, to enable dynamic behavior for instances of classes derived from the DynamicObject class, you must use the dynamic keyword.

    If the expression isn't of type dynamic, static binding will still occur, which is why you're seeing the error.