I'm trying to produce the following JSON structure with JavaScriptSerializer in Net 3.5:
{
"chart": "pie",
"series": [
{
"name": "Browsers",
"data": [
[
"Firefox",
6
],
[
"MSIE",
4
]
],
"size": "43%"
}
]
}
The issue I face is regarding the data section. I cannot seem to create a class that serializes into the above structure in data.
I have read other posts which kind of touch the subject but the solution always seem to be to use JSON.Net. For instance Serializing dictionaries with JavaScriptSerializer. Although, I primaily want to solve it by using the JavaScriptSerializer or other built-in features in the .Net 3.5 framework.
How do I produce the data section?
*EDIT The way to solve it with the JavaScriptSerializer is to create an object array for the data property on the object about to be serialized.
Input parameter data is "Firefox:6\nMSIE:4\nChrome:7".
public object[] GetData(string data) { var dataStrArr = data.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var dataArr = new object[dataStrArr.Length];
for (var index = 0; index < dataStrArr.Length; index++)
{
var component = dataStrArr[index];
var componentArr = component.Split(':');
if (componentArr.Length != 2)
continue;
var key = componentArr[0];
decimal value;
if (decimal.TryParse(componentArr[1], out value))
{
var keyValueArr = new object[2];
keyValueArr[0] = key;
keyValueArr[1] = value;
dataArr[index] = keyValueArr;
}
}
return dataArr;
}