Json structure is returned empty, without property names and values when using Newtonsoft JsonConvert in FB C# client

妖精的绣舞 提交于 2019-12-13 17:22:23

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/14913324/json-structure-is-returned-empty-without-property-names-and-values-when-using-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!