Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return dynamic jsonobject from ASP.NET controller

I'm trying to return a dynamic object deserialized from a json string. At runtime I don't know what the object looks like so I can't type it.

I've tried this:

var json = @"[{""clientNumber"":""3052394"",""accountStatus"":""Active""},{""clientNumber"":""1700630"",""accountStatus"":""Active""}]";
dynamic result = JsonConvert.DeserializeObject(json);
return Json(result, JsonRequestBehavior.AllowGet);

But the result comes out like this:

[[[[]],[[]]],[[[]],[[]]]]

I know I can do this:

var result = new{...};

But this won't work an I don't know what the object is looking like at runtime.

like image 599
wmmhihaa Avatar asked Jan 28 '16 14:01

wmmhihaa


2 Answers

So the standard Controller.Json method in an MVC controller plays strangely with dynamic types.

Just as you did the deserialization with JSON.NET, you'd be better off doing the serialization with JSON.NET too and returning the string output.

return Content(JsonConvert.SerializeObject(dynamicInstance), "application/json");
like image 176
spender Avatar answered Oct 13 '22 13:10

spender


What about Dictionary<string,string> ?

var j = new Dictionary<string,string>();
j.Add("clientNumber","3052394");
j.Add("accountStatus","Active");
return Json(j, JsonRequestBehavior.AllowGet);
like image 35
Avi Fatal Avatar answered Oct 13 '22 13:10

Avi Fatal