Json structure is returned empty, without property

2019-08-03 16:53发布

I'm working on asp.net mvc 4 application which uses Facebook C# SDK (6.0.10.0) and Newtonsoft.Json (4.5.0.0).

Request with FacebookClient returns expando object:

[Authorize]
public ActionResult GetFbData(string path = "me"){
    var expando = this.fb.Get(path);

    return Json(expando);
}

Returned Json looks like:

[{"Key":"id","Value":"100000xxxxxxxx"},{"Key":"name","Value":"John Doe"} ... ]

I want to return it in format {id:100000xxxxxxx, name:"John Doe", ... } so I added this to the code which creates my fb client:

fb.SetJsonSerializers(JsonConvert.SerializeObject,
                      JsonConvert.DeserializeObject);

Same code from above now returns:

[[[]],[[]],[[]],[[]],[[]],[[]],[[[[]],[[]]]],[[[[]],[[]]]],[[]],[[]],[[[[[[[]],[[]]...]

I can get desired result with:

return Content(JsonConvert.SerializeObject(Expando));

This returns proper Json, but Content-Type is text/html; charset=utf-8, and I'm wondering how I can return the desired format as JsonResult without manually setting response headers etc, I just want to change default serialization behavior without re-implementing serializer etc.

There must be something simple that is done with single line of code to change this behavior, and I'm hoping that someone already found it.

2条回答
闹够了就滚
2楼-- · 2019-08-03 17:25

Not sure if you're still looking for an answer, but you almost had it. Content takes a second parameter that is the content type, so if you change it to be

return Content(JsonConvert.SerializeObject(Expando), "application/json");

it should work as expected

查看更多
等我变得足够好
3楼-- · 2019-08-03 17:38

For anyone that may see this in the future, when I encountered this same bug the root cause was that the Json serialization was failing because there was no explicit type set on my result object.

I.e. inside my Controller get

return Json(res.Data, JsonRequestBehavior.AllowGet); where res.Data was of type object Result<object>.Data instead of a class.

查看更多
登录 后发表回答