serialization - How to serialize c# object array into json object without an array -


i want use jsonconvert.serialize in order serialize c# array class object json non-array object.

public list<employee> employees;

output:

"{\"employees\": {\"name\":\"alex\",\"number\":\"25860340\"}, {\"name\":\"tom\",\"number\":\"94085345\"} }"  

the format have asked in question not valid json, because objects not allowed follow 1 directly unless part of array (see json.org). however, transform employee list dictionary , serialize instead, long had suitable key use. 1 idea use employee number key, example:

var employees = new list<employee> {     new employee { name = "alex", number = "25860340" },     new employee { name = "tom", number = "94085345" } };  var obj = new {     employees = employees.todictionary(e => e.number) };  string json = jsonconvert.serializeobject(obj, formatting.indented); console.writeline(json); 

that give output, close wanted:

{   "employees": {     "25860340": {       "name": "alex",       "number": "25860340"     },     "94085345": {       "name": "tom",       "number": "94085345"     }   } } 

if employee number isn't unique, instead use each employee's position in list key this:

int = 0; var obj = new {     employees = employees.todictionary(e => i++) }; 

this give following output instead:

{   "employees": {     "0": {       "name": "alex",       "number": "25860340"     },     "1": {       "name": "tom",       "number": "94085345"     }   } } 

Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -