0

I am supposed to get the Json Object in specific format like

var dataObject = eval('[{"columns":[{ "title": "NAME"}, { "title": "COUNTY"}],"data":[["John Doe","Fresno"],["Billy","Fresno"],["Tom","Kern"],["King Smith","Kings"]]}]');

Till now I have always returned string from Server side in various format and consumed it in UI using Ajax. How to create Json object and send it to UI in the above shared format ?

JSON structure:

[{
    "columns": [{
        "title": "NAME"
    }, {
        "title": "COUNTY"
    }],
    "data": [
        ["John Doe", "Fresno"],
        ["Billy", "Fresno"],
        ["Tom", "Kern"],
        ["King Smith", "Kings"]
    ]
}]
9
  • 3
    Create a class on the server side that reflects the structure you need and then serialize it with JavaScriptSerializer or even better use the json.net serializer. Commented Jul 29, 2016 at 14:41
  • Use 3rd party libraries for json converting like Json.Net - read their documentation about serializing to and from json or use built-in microsoft json serializer msdn.microsoft.com/en-us/library/… Commented Jul 29, 2016 at 14:42
  • 1
    You shouldn't use eval here. Use JSON.parse or better, put an object literal there. Commented Jul 29, 2016 at 14:43
  • 2
    as a side note, the java function eval should be avoided whenever possible as it executes ANY text found as code, which is horribly insecure. JSON.parse is a much better alternative Commented Jul 29, 2016 at 14:43
  • 2
    duplicate of stackoverflow.com/questions/1056121/…, stackoverflow.com/questions/14828520/… and probably several others Commented Jul 29, 2016 at 14:44

1 Answer 1

2

You can use the JavaScriptSerializer class to do this for you.

var myObject = new MyModel();
var serializer = new JavaScriptSerializer();
var dataObject = serializer.Serialize(myObject);

Edit: Your model could look something like this:

public class MyModel
{
   List<string> Titles { get; set; }

   List<KeyValuePair> Data { get; set; }
}

Of course, you could use custom types for Titles and Data where you could define "title" properties (for Columns) and Name & City(?) properties (for Data). Using Lists (or whichever IEnumerable you prefer) will get you the structure you're looking for, though. Hope that helps!

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.