Deserialize json object into dynamic object using Json.net

后端 未结 8 1727
感情败类
感情败类 2020-11-21 22:07

Is it possible to return a dynamic object from a json deserialization using json.net? I would like to do something like this:

dynamic jsonResponse = JsonConv         


        
8条回答
  •  遇见更好的自我
    2020-11-21 22:36

    As of Json.NET 4.0 Release 1, there is native dynamic support:

    [Test]
    public void DynamicDeserialization()
    {
        dynamic jsonResponse = JsonConvert.DeserializeObject("{\"message\":\"Hi\"}");
        jsonResponse.Works = true;
        Console.WriteLine(jsonResponse.message); // Hi
        Console.WriteLine(jsonResponse.Works); // True
        Console.WriteLine(JsonConvert.SerializeObject(jsonResponse)); // {"message":"Hi","Works":true}
        Assert.That(jsonResponse, Is.InstanceOf());
        Assert.That(jsonResponse, Is.TypeOf());
    }
    

    And, of course, the best way to get the current version is via NuGet.

    Updated (11/12/2014) to address comments:

    This works perfectly fine. If you inspect the type in the debugger you will see that the value is, in fact, dynamic. The underlying type is a JObject. If you want to control the type (like specifying ExpandoObject, then do so.

    enter image description here

提交回复
热议问题