In the development process, it is sometimes necessary to convert the JSON string to a dictionary type, or vice versa, usually. NET open source class library Newtonsoft.json to serialize, here I also use this, but I prefer to write extension method convenient in the project call.
Start by creating a new extension class Jsonextensions (the class name is defined by its own liking):
Public Static classjsonextensions {/// <summary> ///serializing a dictionary type to a JSON string/// </summary> /// <typeparam name= "TKey" >Dictionary key</typeparam> /// <typeparam name= "TValue" >Dictionary value</typeparam> /// <param name= "Dict" >the dictionary data to serialize</param> /// <returns>JSON string</returns> Public Static stringSerializedictionarytojsonstring<tkey, Tvalue> (Idictionary<tkey, tvalue>dict) { if(Dict. Count = =0) return ""; stringJsonstr =Jsonconvert.serializeobject (dict); returnJsonstr; } /// <summary> ///deserialize a JSON string into a dictionary type/// </summary> /// <typeparam name= "TKey" >Dictionary key</typeparam> /// <typeparam name= "TValue" >Dictionary value</typeparam> /// <param name= "Jsonstr" >JSON string</param> /// <returns>Dictionary Data</returns> Public StaticIdictionary<tkey, tvalue> Deserializestringtodictionary<tkey, tvalue> (stringjsonstr) { if(string. IsNullOrEmpty (JSONSTR))return NewDictionary<tkey, tvalue>(); Dictionary<tkey, tvalue> jsondict = Jsonconvert.deserializeobject<dictionary<tkey, TValue>>(JSONSTR); returnjsondict; } }
Next call these two extension methods, see if it is feasible, here I write a unit test, convenient for testing, write general, you can go back to the test:
[TestClass]
Public classdictionarytest {[TestMethod] Public voidcan_serialize_deserialize () {Dictionary<string,string> paramdictionary =Newdictionary<string,string>(); Paramdictionary.add (" One","ProductName"); Paramdictionary.add (" Both","ProductColor"); Paramdictionary.add ("three", DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss")); Paramdictionary.add (" Four", DateTime.Now.AddDays (5). ToString ("YYYY-MM-DD HH:mm:ss")); stringJsonstr = jsonextensions.serializedictionarytojsonstring<string,string>(paramdictionary); varJsondict = jsonextensions.deserializestringtodictionary<string,string>(JSONSTR); List<string> Dict1 =Newlist<string>(); foreach(varIteminchparamdictionary) {Dict1. ADD (Paramdictionary[item. Key]); } List<string> dict2 =Newlist<string>(); foreach(varIteminchjsondict) {Dict2. ADD (Jsondict[item. Key]); } intintersect = Dict1. Intersect (DICT2). Count ();//intersection intexcept = Dict1. Except (DICT2). Count ();//Difference Set intUnion = Dict1. Union (DICT2). Count ();//and setAssert.AreEqual (4, intersect); Assert.AreEqual (0, except); Assert.AreEqual (4, Union); Assert.AreEqual ("ProductName", dict2[0]); Assert.AreEqual ("ProductColor", dict2[1]); Assert.AreEqual (4, Dict2. Count); } }
Output Result:
--Fish head tail
qq:875755898
Conversion of JSON string and dictionary type to each other