0

Short version: How can I deserialize a JSON string into a C# list or DataTable without having a defined class to deserialize to?

More explanation: My controller expects a json string which is an array of objects but the properties of the object is unknown. I need to deserialize it into a list and loop through its contents for saving. Sample json strings:
1.

[
    {"id":"10","name":"User","add":false,"edit":true,"authorize":true,"view":true},
    {"id":"11","name":"Group","add":true,"edit":false,"authorize":false,"view":true},
    {"id":"12","name":"Permission","add":true,"edit":true,"authorize":true,"view":true}
]

2.

[
    {"id":"10","name":"User"},
    {"id":"11","name":"Group"},
    {"id":"12","name":"Permission"}
]
super-user
  • 1,017
  • 4
  • 17
  • 41
  • May be [`Dynamic`](http://www.dotnetperls.com/dynamic) should help you – Mohit S Jul 15 '16 at 02:27
  • Possible duplicate with http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object. – Tetsuya Yamamoto Jul 15 '16 at 02:31
  • If after deserialize it need loop through its contents for saving, unless you knowing the mapping of the fields like first field = saving field 1, second field =saving field 2, etc. Else I rather define a class to deserialize it. – Harris Yer Jul 15 '16 at 02:40

2 Answers2

3
dynamic jsonObject = System.Web.Helpers.Json.Decode(jsonText);
Tommy
  • 3,044
  • 1
  • 14
  • 13
  • Beautiful! This allowed me to convert my web api to partial response by combining this answer with dotarj's solution (https://github.com/dotarj/PartialResponse). Many thanks! – Donny McCoy Apr 04 '17 at 20:11
0

Deserialize your Json and cast it directly to datatable.

DataTable dt = (DataTable)JsonConvert.DeserializeObject(jsonText, (typeof(DataTable)));

Refer to this answer : https://stackoverflow.com/a/27282579/4827151

Community
  • 1
  • 1
Anonymous Duck
  • 2,942
  • 1
  • 12
  • 35