c# - How to return JSon object -


i using jquery plugin need json object following structure(i retrieving values database):

{ results: [     { id: "1", value: "abc", info: "abc" },     { id: "2", value: "jkl", info: "jkl" },     { id: "3", value: "xyz", info: "xyz" } ] } 

here class:

public class results {     int _id;     string _value;     string _info;      public int id     {                 {             return _id;         }         set         {             _id = value;         }     }     public string value     {                 {             return _value;         }         set         {             _value = value;         }     }     public string info     {                 {             return _info;         }         set         {             _info = value;         }     } } 

this way serialize it:

results result = new results(); result.id = 1; result.value = "abc"; result.info = "abc"; string json = jsonconvert.serializeobject(result); 

but return 1 row. can please me in returning more 1 result? how can result in format specified above?

first of all, there's no such thing json object. you've got in question javascript object literal (see here great discussion on difference). here's how go serializing you've got json though:

i use anonymous type filled results type:

string json = jsonconvert.serializeobject(new {     results = new list<result>()     {         new result { id = 1, value = "abc", info = "abc" },         new result { id = 2, value = "jkl", info = "jkl" }     } }); 

also, note generated json has result items ids of type number instead of strings. doubt problem, easy enough change type of id string in c#.

i'd tweak results type , rid of backing fields:

public class result {     public int id { ;set; }     public string value { get; set; }     public string info { get; set; } } 

furthermore, classes conventionally pascalcased , not camelcased.

here's generated json code above:

{   "results": [     {       "id": 1,       "value": "abc",       "info": "abc"     },     {       "id": 2,       "value": "jkl",       "info": "jkl"     }   ] } 

Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -