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;
}
I think you need something like the following class (RootObject) to serialize that:
public class Series
{
public string name { get; set; }
public List<List<object>> data { get; set; }
public string size { get; set; }
}
public class RootObject
{
public string chart { get; set; }
public List<Series> series { get; set; }
}
Let me know if that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With