简体   繁体   English

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

[英]Using ServiceStack.Text to deserialize a json string to object

I have a JSON string that looks like: 我有一个JSON字符串,看起来像:

"{\"Id\":\"fb1d17c7298c448cb7b91ab7041e9ff6\",\"Name\":\"John\",\"DateOfBirth\":\"\\/Date(317433600000-0000)\\/\"}"

I'm trying to deserialize it to object (I'm implementing a caching interface) 我正在尝试将其反序列化为object (我正在实现一个缓存接口)

The trouble I'm having is when I use 我遇到的麻烦就是我用的时候

JsonSerializer.DeserializeFromString<object>(jsonString);

It's coming back as 它回来了

"{Id:6ed7a388b1ac4b528f565f4edf09ba2a,Name:John,DateOfBirth:/Date(317433600000-0000)/}" “{ID:6ed7a388b1ac4b528f565f4edf09ba2a,名称:约翰,出生日期:/日期(317433600000-0000)/}”

Is that right? 是对的吗?

I can't assert on anything... I also can't use the dynamic keyword.... 我无法断言任何事情......我也不能使用动态关键字....

Is there a way to return an anonymous object from the ServiceStack.Text library? 有没有办法从ServiceStack.Text库返回一个匿名对象?

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, eg deserializing an object with: ServiceStack.Common中使用JS Utils是使用未知类型反序列化adhoc JSON的首选方法,因为它将根据JSON有效负载返回相关的C#对象,例如使用以下命令反序列化对象:

var obj = JSON.parse("{\"Id\":\"..\"}");

Will return a loose-typed Dictionary<string,object> which you can cast to access the JSON object dynamic contents: 将返回一个松散类型的Dictionary<string,object> ,您可以将其转换为访问JSON对象的动态内容:

if (obj is Dictionary<string,object> dict) {
    var id = (string)dict["Id"];
}

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.Text类型的JSON序列化程序,则它无法反序列化为对象,因为它不知道要反序列化的类型,因此它将其保留为作为对象的字符串。

Consider using ServiceStack's dynamic APIs to deserialize arbitrary JSON, eg: 考虑使用ServiceStack的动态API来反序列化任意JSON,例如:

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();

Or parsing into a dynamic: 或解析为动态:

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);

Another option is to tell ServiceStack to convert object types to a Dictionary, eg: 另一种选择是告诉ServiceStack将对象类型转换为Dictionary,例如:

JsConfig.ConvertObjectTypesIntoStringDictionary = true;
var map = (Dictionary<string, object>)json.FromJson<object>();
map.PrintDump();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM