是否可以使用json.net从json反序列化返回动态对象? 我想做这样的事情:
dynamic jsonResponse = JsonConvert.Deserialize(json);
Console.WriteLine(jsonResponse.message);
#1楼
从Json.NET 4.0 Release 1开始,提供了本机动态支持:
[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>());
}
而且,当然,获取当前版本的最佳方法是通过NuGet。
已于2014年11月12日更新以解决评论:
这工作得很好。 如果您在调试器中检查类型,则实际上该值是dynamic 。 基础类型是JObject
。 如果要控制类型(例如指定ExpandoObject
,则可以这样做)。

#2楼
是的,您可以使用JsonConvert.DeserializeObject做到这一点。 为此,只需执行以下操作:
dynamic jsonResponse = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonResponse["message"]);
#3楼
如果只是反序列化为动态,则将获得JObject。 您可以使用ExpandoObject获得所需的内容。
var converter = new ExpandoObjectConverter();
dynamic message = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, converter);
#4楼
如果您将JSON.NET与不是JObject的旧版本一起使用。
这是从JSON制作动态对象的另一种简单方法: https : //github.com/chsword/jdynamic
NuGet安装
PM> Install-Package JDynamic
支持使用字符串索引访问成员,例如:
dynamic json = new JDynamic("{a:{a:1}}");
Assert.AreEqual(1, json["a"]["a"]);
测试用例
您可以按以下方式使用此实用程序:
直接获取价值
dynamic json = new JDynamic("1");
//json.Value
2,在json对象中获取成员
dynamic json = new JDynamic("{a:'abc'}");
//json.a is a string "abc"
dynamic json = new JDynamic("{a:3.1416}");
//json.a is 3.1416m
dynamic json = new JDynamic("{a:1}");
//json.a is integer: 1
3.IEnumerable
dynamic json = new JDynamic("[1,2,3]");
/json.Length/json.Count is 3
//And you can use json[0]/ json[2] to get the elements
dynamic json = new JDynamic("{a:[1,2,3]}");
//json.a.Length /json.a.Count is 3.
//And you can use json.a[0]/ json.a[2] to get the elements
dynamic json = new JDynamic("[{b:1},{c:1}]");
//json.Length/json.Count is 2.
//And you can use the json[0].b/json[1].c to get the num.
其他
dynamic json = new JDynamic("{a:{a:1} }");
//json.a.a is 1.
#5楼
注意:在2010年我回答这个问题时,没有某种类型就无法反序列化,这使您无需定义实际的类即可进行反序列化,并允许使用匿名类进行反序列化。
您需要某种反序列化的类型。 您可以按照以下方式进行操作:
var product = new { Name = "", Price = 0 };
dynamic jsonResponse = JsonConvert.Deserialize(json, product.GetType());
我的答案基于.NET 4.0在JSON序列化器中构建的解决方案。 反序列化为匿名类型的链接在这里:
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3162926