.net 在 C# 中将 json 反序列化为匿名对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6671972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deserializing json to anonymous object in c#
提问by Shawn Mclean
How do I convert a string of json formatted data into an anonymous object?
如何将一串 json 格式的数据转换为匿名对象?
采纳答案by agent-j
回答by i31nGo
using dynamics is something like this:
使用动力学是这样的:
string jsonString = "{\"dateStamp\":\"2010/01/01\", \"Message\": \"hello\" }";
dynamic myObject = JsonConvert.DeserializeObject<dynamic>(jsonString);
DateTime dateStamp = Convert.ToDateTime(myObject.dateStamp);
string Message = myObject.Message;
回答by Horitsu
vb.net using Newtonsoft.Json :
vb.net 使用 Newtonsoft.Json :
dim jsonstring = "..."
dim foo As JObject = JObject.Parse(jsonstring)
dim value1 As JToken = foo("key")
e.g.:
dim jsonstring = "{"MESSAGE":{"SIZE":"123","TYP":"Text"}}"
dim foo = JObject.Parse(jsonstring)
dim messagesize As String = foo("MESSAGE")("SIZE").ToString()
'now in messagesize is stored 123 as String
So you don't need a fixed structure, but you need to know what you can find there.
所以你不需要一个固定的结构,但你需要知道你能在那里找到什么。
But if you don't even know what is inside, than you can enumerate thru that JObject with the navigation members e.g. .first(), .next() E.g.: So you could implement a classical depth-first search and screening the JObject
但是,如果您甚至不知道里面是什么,那么您可以通过导航成员枚举该 JObject,例如 .first(), .next() 例如:因此您可以实现经典的深度优先搜索并筛选 JObject
(for converting vb.net to c#: http://converter.telerik.com/)
(用于将 vb.net 转换为 c#:http: //converter.telerik.com/)
回答by Paul Totzke
using Newtonsoft.Json, use DeserializeAnonymousType:
使用 Newtonsoft.Json,使用 DeserializeAnonymousType:
string json = GetJsonString();
var anonType = new { Order = new Order(), Account = new Account() };
var anonTypeList = new []{ anonType }.ToList(); //Trick if you have a list of anonType
var jsonResponse = JsonConvert.DeserializeAnonymousType(json, anonTypeList);
Based my answer off of this answer: https://stackoverflow.com/a/4980689/1440321
基于我对这个答案的回答:https: //stackoverflow.com/a/4980689/1440321
回答by Davy8
I think the closest you can get is dynamicin .NET 4.0
我认为你能得到的最接近的是dynamic.NET 4.0
The reason anonymous objects wouldn't work is because they're still statically typed, and there's no way for the compiler to provide intellisense for a class that only exists as a string.
匿名对象不起作用的原因是因为它们仍然是静态类型的,并且编译器无法为仅作为字符串存在的类提供智能感知。

