如何使用JsonResult获取字典的JSON字符串? [英] How do I use JsonResult to get JSON string of Dictionary?
本文介绍了如何使用JsonResult获取字典的JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我有一个MVC应用程序,其中我有以下字典:
Hi All,
I am having a MVC application in which I am having following dictionary :
Dictionary<int, List<user>> foo = new Dictionary<int, List<user>>();
class user
{
public int test1 { get; set; }
public int test2 { get; set; }
}
如何在将数据分配到字典后获取json字符串。
感谢你提前的建议。
-Avinash
How to get json string after assigning data to dictionary.
Thanks for your suggestions in advance.
-Avinash
推荐答案
你需要将你的字典序列化为JSON字符串,我是对的吗?
那么你可以使用这样的东西..
You need to serialize your dictionary to JSON string, am i right?
then you can use something like this..
Dictionary> foo = new Dictionary>();
foo.Add(1, new List() { new user() { test1 = 1, test2 = 1 }
, new user() { test1 = 2, test2 = 2 } });
foo.Add(2, new List() { new user() { test1 = 3, test2 = 3 }
, new user() { test1 = 4, test2 = 4 } });
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
它会填充你的json字符串......
it will populating your json string like this...
{"1":[{"test1":1,"test2":1},{"test1":2,"test2":2}],"2":[{"test1":3,"test2":3},{"test1":4,"test2":4}]}
我使用Newtonsoft.Json库来序列化你的对象,你可以从这里使用这个nuget包。 />
https://www.nuget.org/packages/Newtonsoft.Json/ [ ^ ]
referance: http://www.newtonsoft.com/json [ ^ ]
这篇关于如何使用JsonResult获取字典的JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文