Deserialize JSON string to Dictionary<string,object>

Viewed 99193

I have this string:

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

I'm deserializing the object:

object json = jsonSerializer.DeserializeObject(jsonString);

The object looks like:

object[0] = Key: "processLevel", Value: "1"
object[1] = Key: "segments", Value: ...

And trying to create a dictionary:

Dictionary<string, object> dic = json as Dictionary<string, object>;

but dic gets null.

What can be the issue ?

5 Answers

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<T1,T2> 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<FirstPageSectionModel, List<FirstPageContent>> 
    { 

    }

Step 3) Replace Dictionary and List

public Dictionary<FirstPageSectionModel, List<FirstPageContent>> Sections { get; set; }

and

 public List<SectionDictionary> 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<FirstPageByPlatformFinalV2>(str);
 }

Thanks a lot

Related