Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,
I am having a MVC application in which I am having following dictionary :

C#
Dictionary<int, List<user>> foo = new Dictionary<int, List<user>>();

class user
    {
        public int test1 { get; set; }
        public int test2 { get; set; }
    }


How to get json string after assigning data to dictionary.

Thanks for your suggestions in advance.

-Avinash
Posted
Comments
Tejas Vaishnav 27-Jan-15 8:45am    
Please rate my answer...

1 solution

You need to serialize your dictionary to JSON string, am i right?

then you can use something like this..

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


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}]}


I have use Newtonsoft.Json library to serialize your object, you can use this nuget package from here
https://www.nuget.org/packages/Newtonsoft.Json/[^]

referance : http://www.newtonsoft.com/json[^]
 
Share this answer
 
Comments
BillWoodruff 28-Jan-15 5:11am    
+3 This is the start of a good answer, but, the code shown will not compile as-is.

Fix the code syntax, and give a brief example of the required syntax (not obvious) used to de-serialize a NewtonSoft flavor JSON Dictionary ... and you get my #5 :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900