none
How to convert a System.Json.JsonValue to a dictionary<string, object> RRS feed

  • Question

  • I am using System.Json.JsonValue.Parse to deserialize a Json string. It returns a JsonValue object. I couldn't find any examples on how to convert that JsonValue object to a dictionary<string, object>.

    I found examples on how to do this using the newtonsoft implementation, but I would like to use System.Json.

    Any help would be greatly appreciated.

    Best regards,

    Christophe

    Sunday, March 3, 2019 5:21 AM

Answers

  • It is easier to obtain the next dictionary:

       string example = "{ \"name1\" : \"text1\", \"name2\" : [\"item1\", \"item2\"] }";

     

       JsonValue v = JsonValue.Parse( example );

       IDictionary<string, JsonValue> d = v as IDictionary<string, JsonValue>;

     

    If it is not a dictionary, then d is null.

    If you need a Dictionary<string, object>:

       Dictionary<string, object> d2 = d.ToDictionary( p => p.Key, p => (object)p.Value );


    • Edited by Viorel_MVP Sunday, March 3, 2019 8:22 AM
    • Marked as answer by ccaltagi Tuesday, March 12, 2019 1:53 PM
    Sunday, March 3, 2019 8:19 AM

All replies

  • It is easier to obtain the next dictionary:

       string example = "{ \"name1\" : \"text1\", \"name2\" : [\"item1\", \"item2\"] }";

     

       JsonValue v = JsonValue.Parse( example );

       IDictionary<string, JsonValue> d = v as IDictionary<string, JsonValue>;

     

    If it is not a dictionary, then d is null.

    If you need a Dictionary<string, object>:

       Dictionary<string, object> d2 = d.ToDictionary( p => p.Key, p => (object)p.Value );


    • Edited by Viorel_MVP Sunday, March 3, 2019 8:22 AM
    • Marked as answer by ccaltagi Tuesday, March 12, 2019 1:53 PM
    Sunday, March 3, 2019 8:19 AM
  • Hi ccaltagi,

    Thank you for posting here.

    I make a simple example for your reference.

      string JSON = @"{'1':'A','2':'B','3':'C','4':'D'}";
                var restoredDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(JSON);


    For better conversion, to get the json data from the Dictionary is a good choice to avoid errors.

     var myd = new Dictionary<string, string>();
                myd.Add("1", "A");
                myd.Add("2", "B");
    
                var JSON= JsonConvert.SerializeObject(myd);

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, March 4, 2019 6:15 AM
    Moderator
  • Thanks so much. That's exactly what I was looking for!
    Tuesday, March 12, 2019 1:54 PM