gpt4 book ai didi

c# - 从 json 中反序列化 Dictionary,可能没有 Newtonsoft.Json?

转载 作者:行者123 更新时间:2023-11-30 16:12:09 26 4
gpt4 key购买 nike

帮我反序列化 Dictionary 对象。

例如我有我的课

[Serializable]
public class MyClass
{
/// <summary>
/// some class variables
/// </summary>
public string variable_A;

public decimal variable_B;

/// <summary>
/// constructor for example
/// </summary>
public MyClass(string s, decimal d)
{
variable_A = s;
variable_B = d;
}
}

然后我创建了字典——以字符串为键,以 MyClass 对象为值:

Dictionary<string, MyClass> myDictionary = new Dictionary<string, MyClass>
{
{ "key1", new MyClass("some string value", 5) },
{ "key2", new MyClass("some string value", 3) },
{ "key3", new MyClass("some string value", 10) }
};

这里我序列化这些数据以传输到其他地方:

        string myObjectJson = new JavaScriptSerializer().Serialize(myDictionary);
Console.WriteLine(myObjectJson);

但是我该如何进行反向操作 - 将此数据反序列化回我的 Dictionary 对象?

我试过像这样使用 DeserializeObject:

    JavaScriptSerializer js = new JavaScriptSerializer();
Dictionary<string, MyClass> dict = (Dictionary<string, Object>)js.DeserializeObject(myObjectJson);


//// Also tried this method, but it describes deserialize to Dictionary<string, string>, but I have my object in value, not string
//// http://stackoverflow.com/questions/4942624/how-to-convert-dictionarystring-object-to-dictionarystring-string-in-c-sha

//// p.s.: don't want to use third-party dll's, like Json.Net
//// http://stackoverflow.com/questions/19023696/deserialize-dictionarystring-t

最佳答案

您应该使用通用重载:

var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, MyClass>>(myObjectJson);

还要确保 MyClass 类型具有默认构造函数。

关于c# - 从 json 中反序列化 Dictionary<string, MyClass>,可能没有 Newtonsoft.Json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23375992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com