Deserialize json object into dynamic object using Json.net

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 = JsonConvert.Deserialize(json);
Console.WriteLine(jsonResponse.message);

latest json.net version allow do this:

dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");

Console.WriteLine(d.number);
Console.WriteLine(d.str);
Console.WriteLine(d.array.Count);

output:

 1000
 string
 6

Documentation here: LINQ to JSON with Json.NET


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<dynamic>());
    Assert.That(jsonResponse, Is.TypeOf<JObject>());
}

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.

在这里输入图像描述


If you just deserialize to dynamic you will get a JObject back. You can get what you want by using an ExpandoObject.

var converter = new ExpandoObjectConverter();    
dynamic message = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, converter);
链接地址: http://www.djcxy.com/p/20068.html

上一篇: 如何在使用json.net的情况下忽略类中的属性

下一篇: 使用Json.net将json对象反序列化为动态对象