Conversion of JSON string and dictionary type to each other

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.