我有一个如下所示的JSON字符串:
I have a JSON string that looks like:
"{\"Id\":\"fb1d17c7298c448cb7b91ab7041e9ff6\",\"Name\":\"John\",\"DateOfBirth\":\"\\/Date(317433600000-0000)\\/\"}"我正在尝试将其反序列化为object(我正在实现一个缓存接口)
I'm trying to deserialize it to object (I'm implementing a caching interface)
我遇到的麻烦是使用
JsonSerializer.DeserializeFromString<object>(jsonString);它又回来了
"{{Id:6ed7a388b1ac4b528f565f4edf09ba2a,名称:John,DateOfBirth:/Date(317433600000-0000)/}"
"{Id:6ed7a388b1ac4b528f565f4edf09ba2a,Name:John,DateOfBirth:/Date(317433600000-0000)/}"
对吗?
我什么都不能断言...我也不能使用dynamic关键字....
I can't assert on anything... I also can't use the dynamic keyword....
是否可以从ServiceStack.Text库返回匿名对象?
Is there a way to return an anonymous object from the ServiceStack.Text library?
推荐答案使用 JS Utils 是反序列化具有未知类型的即席JSON的首选方法,因为它将基于JSON有效负载返回相关的C#对象,例如,使用以下方法反序列化一个对象:
Using the JS Utils in ServiceStack.Common is the preferred way to deserialize adhoc JSON with unknown types since it will return the relevant C# object based on the JSON payload, e.g deserializing an object with:
var obj = JSON.parse("{\"Id\":\"..\"}");将返回一个松散类型的Dictionary<string,object>,您可以将该类型强制转换为访问JSON对象动态内容:
Will return a loose-typed Dictionary<string,object> which you can cast to access the JSON object dynamic contents:
if (obj is Dictionary<string,object> dict) { var id = (string)dict["Id"]; }但是,如果您更喜欢使用 ServiceStack.Text 类型的JSON序列化器,则不能反序列化为对象,因为它不知道反序列化为哪种类型,因此将其保留为对象的字符串.
But if you prefer to use ServiceStack.Text typed JSON serializers, it can't deserialize into an object since it doesn't know what type to deserialize into so it leaves it as a string which is an object.
考虑使用 ServiceStack的动态API 来反序列化任意JSON,例如:
Consider using ServiceStack's dynamic APIs to deserialize arbitrary JSON, e.g:
var json = @"{\"Id\":\"fb1d17c7298c448cb7b91ab7041e9ff6\", \"Name\":\"John\",\"DateOfBirth\":\"\\/Date(317433600000-0000)\\/\"}"; var obj = JsonObject.Parse(json); obj.Get<Guid>("Id").ToString().Print(); obj.Get<string>("Name").Print(); obj.Get<DateTime>("DateOfBirth").ToLongDateString().Print();或解析为动态文件:
dynamic dyn = DynamicJson.Deserialize(json); string id = dyn.Id; string name = dyn.Name; string dob = dyn.DateOfBirth; "DynamicJson: {0}, {1}, {2}".Print(id, name, dob);另一种选择是告诉ServiceStack将对象类型转换为字典,例如:
Another option is to tell ServiceStack to convert object types to a Dictionary, e.g:
JsConfig.ConvertObjectTypesIntoStringDictionary = true; var map = (Dictionary<string, object>)json.FromJson<object>(); map.PrintDump();更多推荐
使用ServiceStack.Text将json字符串反序列化为对象
发布评论