Decode JSON string containing JSON string

3

I have to decode a JSON string containing another JSON string on it. Currently I'm trying to decode it into a Dictionary<string,string> using Serializator.Deserialize<Dictionary<string,string>>(value) from System.Web.Script.Serialization, but haven't succeed.

This is the string:

{
      "label": "Side",
      "options": [
        {
          "key": "left",
          "value": 0
        },
        {
          "key": "right",
          "value": 1
        }
      ]
}

And this is the format error I get from the decoder:

(System.ArgumentException HResult=0x80070057 Message=Invalid object passed in, ':' or '}' expected. (34): {"label": "Side", "options": "[{"key": "left", "value": 0},{"key":"right", "value":1}]"} Source=System.Web.Extensions) Which means he gets "[{" as a string and thus fails to convert of course...

Is there any way I can decode this specific JSON string and store it in an object? Client is very specific about this JSON format... Thanks a lot

c#
json
json-deserialization
asked on Stack Overflow Oct 30, 2018 by ACleCas • edited Oct 30, 2018 by godot

3 Answers

1

Represent your json like that:

{
  "label": "Side",
  "options": "[{ 'key': 'left', 'value': '0'},{ 'key':'right', 'value':1}]"
}

inside json with single quotes

let's assume you have this two classes :

public class YourObject
    {
        public string label { get; set; }
        public string options { get; set; }
    }
    public class InsideObject
    {
        public string key { get; set; }
        public int value { get; set; }
    }

so your json has another json as as string under the key "options" and you can extract both of them like that:

 string json = "{\"label\": \"Side\", \"options\": \"[{ 'key': 'left', 'value': '0'},{ 'key':'right', 'value':1}]\"}";
 var jsonObj = JsonConvert.DeserializeObject<YourObject>(json);
 var insideObj = JsonConvert.DeserializeObject<InsideObject>(jsonObj.options);

P.S here used Newtonsoft

answered on Stack Overflow Oct 30, 2018 by godot • edited Oct 30, 2018 by godot
0

Finally I used string format as follows:

{
  "label": "Side",
  "options": [
    {
      "key": "left",
      "value": 0
    },
    {
      "key": "right",
      "value": 1
    }
  ]
}

and store all the JSON in a Dictionary< string, object >. I will then implement a method to decode the object inside the JSON.

answered on Stack Overflow Oct 30, 2018 by ACleCas • edited Oct 30, 2018 by godot
-1

As Matt already mentioned in his comment your JSON is invalid, instead of "[{"key" it should be [{"key" and instead of }]"} it should be }]}.

answered on Stack Overflow Oct 30, 2018 by Markus Safar

User contributions licensed under CC BY-SA 3.0