使用ServiceStack.Text将json字符串反序列化为对象

编程入门 行业动态 更新时间:2024-10-27 11:24:46
本文介绍了使用ServiceStack.Text将json字符串反序列化为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个如下所示的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字符串反序列化为对象

本文发布于:2023-11-17 07:43:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609340.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   序列   对象   ServiceStack   Text

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!