5

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;
    }
Community
  • 1
  • 1
Tobias Nilsson
  • 512
  • 2
  • 13
  • possible duplicate of [Serializing dictionaries with JavaScriptSerializer](http://stackoverflow.com/questions/6416950/serializing-dictionaries-with-javascriptserializer) – McGarnagle Nov 05 '12 at 22:28
  • The post you linked to has a native .Net solution (overriding the serializer). Still, much easier to familiarize yourself with JSON.Net ... – McGarnagle Nov 05 '12 at 22:29
  • Presumably he's constrained technologically if he's still using .net 3.5, may not have the option of JSON.Net. – Pxtl Oct 02 '16 at 00:13

1 Answers1

1

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.

Sergio S
  • 194
  • 7