0

I have a some data that I need serialized to json. Below is a simplified version of the code I'm using on the backend to generate the json:

public class RawBarData
{
    public string Month { get; set; }
    public decimal Total { get; set; }
}

List<RawBarData> lstData == getData();

string jdata = JsonConvert.SerializedObject(lstData);   

After this runs, jdata looks something like this:

[ 
  { Month: "January", Total: 10}, 
  { Month: "February", Total: 8}, 
  { Month: "March", Total:  4}, 
  { Month: "April", Total: 13}, 
  { Month: "May", Total: 17}, 
  { Month: "June", Total:  9} 
]

However I need the output to look like this:

[ 
  ["January", 10], 
  ["February", 8], 
  ["March", 4], 
  ["April", 13], 
  ["May", 17], 
  ["June", 9] 
]

How can I guide json.net to serialize the data in this format?

1
  • The key to getting things in the correct JSON format is to create a C# object that will serialize how you want it to. Two ways to do this. One is to create a new class and the provide a method to convert to the new class. The second method is to create anonymous objects expressly for the purpose of serializing (like recursive's answer). Commented Apr 17, 2014 at 18:31

1 Answer 1

3

You can do it like this:

List<object[]> converted = getData()
    .Select(r => new object[] { r.Month, r.Total })
    .ToList();
string jdata = JsonConvert.SerializedObject(converted);

This replaces the RawBarData instances with object arrays, which will serialize into... you guessed it, JSON arrays.

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

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.