反序列化的最佳方法是什么
Dictionary<string, object>{
{"fName", "John"},
{"lName", "Doe"},
{"email", "john@doe.net"}
}
对此
class Member{
string fName;
string lName;
string email;
}
最佳答案
如今,NewtonSoft 在 ASP.NET 应用程序中变得如此普遍,以至于如果我需要一个简短而甜蜜的解决方案来解决这种类型的映射,我可以使用一些这样的代码。当然,如果第三方库尚不存在,则引入第三方库可能会被滥用,但有时我们只是使用有效的库。 Newtonsoft 做到了!
using Newtonsoft.Json;
class SerializationTests
{
public void DictionarySerializeSample()
{
var dict = new Dictionary<string, object>
{
{"fName", "John"},
{"lName", "Doe"},
{"email", "john@doe.net"}
};
string dictInJson = JsonConvert.SerializeObject(dict);
var member = JsonConvert.DeserializeObject<Member>(dictInJson);
// use Newtonsoft to write out the object re-serialized
Console.WriteLine(JsonConvert.SerializeObject(member, Formatting.Indented));
}
public class Member
{
public string fName;
public string lName;
public string email;
}
}
关于c# - Asp.Net 将 Dictionary<string, object> 反序列化为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3782326/