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"}
]
3
  • May be Dynamic should help you Commented Jul 15, 2016 at 2:27
  • Possible duplicate with stackoverflow.com/questions/3142495/…. Commented Jul 15, 2016 at 2: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. Commented Jul 15, 2016 at 2:40

2 Answers 2

3
dynamic jsonObject = System.Web.Helpers.Json.Decode(jsonText);
Sign up to request clarification or add additional context in comments.

1 Comment

Beautiful! This allowed me to convert my web api to partial response by combining this answer with dotarj's solution (github.com/dotarj/PartialResponse). Many thanks!
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

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.