反序列化字典数组

发布于 2024-10-29 04:14:11 字数 519 浏览 2 评论 0原文

我得到一个带有字符串的 JSON 对象,如下所示:

"rec":[
    {"f":["T","R"],"u":316,"fName":"test","lName":"test2"},
    {"f":["C","R"],"u":990,"fName":"beth","lName":"tin"}
],

我正在尝试使用 DataContractSerializer 并将 DataMember 合约转换为 public Dictionary类型的成员来对其进行反序列化。 [] rec; 但我收到如下错误:

“System.Object”类型的对象不能 被转换为类型 'System.Collections.Generic.Dictionary`2[System.String,System.Object]'。

有人可以向我解释一下我应该如何反序列化这个字符串吗?

I'm getting a JSON object with an string like:

"rec":[
    {"f":["T","R"],"u":316,"fName":"test","lName":"test2"},
    {"f":["C","R"],"u":990,"fName":"beth","lName":"tin"}
],

I'm trying to de-serialize it using the DataContractSerializer and by having a DataMember contract into a member of type public Dictionary<string,object> [] rec; But i get an error like:

Object of type 'System.Object' cannot
be converted to type
'System.Collections.Generic.Dictionary`2[System.String,System.Object]'.

Can someone explain to me how I should go about deserializing this string ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

佞臣 2024-11-05 04:14:28

我认为你应该使用 JavaScriptSerializer:

var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<Dictionary<string, object>>("{" + data + "}")

I think you should use the JavaScriptSerializer:

var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<Dictionary<string, object>>("{" + data + "}")
夜血缘 2024-11-05 04:14:26

为什么不使用 json.net

从他们的文档中反序列化:

string json = @"{""key1"":""value1"",""key2"":""value2""}";

Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

Console.WriteLine(values.Count);
// 2

Console.WriteLine(values["key1"]);
// value1

可以在包含某些 [Json...]-attributes 的类上得到增强...如果您正在使用 DataMember-attributes,您可以直接访问 json.net,因为它们支持使用 DataMember 等...

序列化也应该有效 - 只是尝试过列表和类似的东西,但对我来说效果非常好!

why not use json.net?

deserialization from their docu:

string json = @"{""key1"":""value1"",""key2"":""value2""}";

Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

Console.WriteLine(values.Count);
// 2

Console.WriteLine(values["key1"]);
// value1

which could be enhanced on classes with contain certain [Json...]-attributes ... If you are working with DataMember-attributes, you can go straight for json.net, as they support the usage of DataMember and alikes ...

serialization should work too - just have tried lists and alike-stuff yet which worked more than fine for me!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文