0

I am new to JSON. I am trying to create below JSON format using C#:

series: {
   name: "series1",
   data: [[0,2],[1,3],[2,1],[3,4]]
}

I am struggling with the data part. What should be my .NET code to achieve the above format?

3
  • How is the data stored in your C# code? What have you tried? Commented Feb 17, 2014 at 22:45
  • 2
    Well for starters that is not correct Json Commented Feb 17, 2014 at 22:45
  • You can also use Json.NET to achieve this. It is a popular library for working with Json. Commented Feb 17, 2014 at 22:47

2 Answers 2

2
List<int[]> arr = new List<int[]>()
    {
        new[]{0,2},new[]{1,3},new[]{2,1},new[]{3,4},
    };

var obj = new { data = arr };

string json = JsonConvert.SerializeObject(obj);

OUTPUT: {"data":[[0,2],[1,3],[2,1],[3,4]]}

OR

declare these classes (see http://json2csharp.com/)

public class RootObject
{
    public Series series { get; set; }
}

public class Series
{
    public string name { get; set; }
    public List<List<int>> data { get; set; }
}

create an instance of RootObject, fill the properties, and serialize it.

Sign up to request clarification or add additional context in comments.

Comments

0

Use newtonsoft Json.net to serialize the objects, available via nuget or http://james.newtonking.com/json

Create the objects like this

var seriesContent = new Dictionary<string, object>
{
    {"name", "series1"},
    {"data", new[] {new[]{0,2},new[]{1,3},new[]{2,1},new[]{3,4}}}
};

var series = new Dictionary<string, object>
{
    {"series", seriesContent}
};

var s = JsonConvert.SerializeObject(series);

s will contain

{
    "series": {
        "name": "series1",
        "data": [
            [0, 2],
            [1, 3],
            [2, 1],
            [3, 4]
        ]
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.