ADH ADH - 4 months ago 32
JSON Question

Deserialize JSON When Names Have Brackets and Parentheses

I am consuming JSON from a third party that looks like this:

{"id":"1","[question(21), option(\"10033-other\")]":"","[question(22)]":"electric"}


I understand how to get the values out when the key name is a simple string. But I cannot figure out how to get the values out when the key name is not a basic string. How would I deserialize the [question(21)] and [question(22)] values?

My code is below.

Classes:

public class MyFeed
{
public string id { get; set; }
}

public class MyFeedClass
{
public List<MyFeed> data { get; set; }
}


Program.cs

static void Main(string[] args)
{
string webReq = String.Empty;
webReq += "https://restapi.surveygizmo.com/head/survey/zzzzzzzzz";
webReq += "/surveyresponse/";
webReq += "?user:pass=xxxxxx:yyyyyyyyy";
HttpWebRequest request = WebRequest.Create(webReq) as HttpWebRequest;
var myString = String.Empty;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
myString += reader.ReadToEnd();
}

MyFeedClass myFeedClass =
new JavaScriptSerializer().
Deserialize<MyFeedClass>(myString);

Console.Title = "Bentley - Survey Data Loader";
Console.WriteLine("");
foreach (var item in myFeedClass.data)
{
Console.WriteLine("id: {0}", item.id);
}
Console.WriteLine("");
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}

Answer

Your JSON and your classes don't look like they match up - that said, with a bit of tweaking, you can get something to deserialize out of it:

If we wrap the JSON you posted like so:

string data =  @"{""data"":{""id"":""1"",""[question(21), option(\""10033-other\"")]"":"""",""[question(22)]"":""electric""}}";

(or in non-mangled form)

{"data":{"id":"1","[question(21), option(\"10033-other\")]":"","[question(22)]":"electric"}}

And redefined the feed class thusly:

public class MyFeedClass
{
    public Dictionary<string,string> data { get; set; }
}

new JavaScriptSerializer().Deserialize<MyFeedClass>(data)

Produces a Dictionary<string,string> with contents:

{id, 1 }
{[question(21), option("10033-other")], }
{[question(22)], electric }