4

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?

4

1 回答 1

4

即使DynamicJson.Deserialize确实返回了 的实例DynamicJson,您也必须声明dyndynamic动态处理它:

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

根据DynamicObjectDynamicJson继承自)的文档:

在 C# 中,要为从 DynamicObject 类派生的类的实例启用动态行为,您必须使用 dynamic 关键字

如果表达式不是 type dynamic,静态绑定仍然会发生,这就是您看到错误的原因。

于 2014-09-28T00:07:00.843 回答