Deserialize JSON string to Dictionary

后端 未结 5 1729
长情又很酷
长情又很酷 2020-11-30 04:32

I have this string:

[{ \"processLevel\" : \"1\" , \"segments\" : [{ \"min\" : \"0\", \"max\" : \"600\" }] }]

I\'m deserializing the object:

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 05:22

    I had the same problem and found a solution to it

    • Very simple
    • No bugs
    • Tested on operational product

    Step 1) Create a generic class with 2 property

         public class CustomDictionary where T1:class where T2:class
          {
              public T1 Key { get; set; }
              public T2 Value { get; set; }
          }
    

    Step 2) Create New class and inherit from first class

      public class SectionDictionary: CustomDictionary> 
        { 
    
        }
    

    Step 3) Replace Dictionary and List

    public Dictionary> Sections { get; set; }
    

    and

     public List Sections { get; set; }
    

    Step 4) Serialize or Deserialize easely

     {
         firstPageFinal.Sections.Add(new SectionDictionary { Key= section,Value= contents });
         var str = JsonConvert.SerializeObject(firstPageFinal);
         var obj = JsonConvert.DeserializeObject(str);
     }
    

    Thanks a lot

提交回复
热议问题