問題描述
我的問題是這樣的:
這是從我的 WebAPI 控制器發回的響應.
This is the response being sent back from my WebAPI controller.
"[
[
{"id":"identifier"},
{"name":"foobar"}
]
]"
請注意,響應包含在引號中,并且所有嵌入的引號都被轉義了.這顯然是個問題.我可以向 JSON.NET 序列化程序提供任何設置來防止這種情況發生嗎?
Notice that the response is wrapped in quotations and all of the embedded quotations are escaped. This is obviously a problem. Are there any settings I can provide to the JSON.NET Serializer to prevent this from occurring?
正如 p.s.w.g 在他的回復中猜測的那樣,我使用的是 JSON.NET 的
As p.s.w.g guessed in his response, I was using JSON.NET's
JsonConvert.SerializeObject(instance)
執行我的序列化.
我這樣做是因為在構建自定義轉換器時,我已將它們包含在我的 WepApiConfig 中的 JsonConvert.DefaultSettings 中(我顯然認為這不會成為問題)
I did this because as I was building out my custom Converters, I had included them in the JsonConvert.DefaultSettings within my WepApiConfig (and I obviously thought this would not be a problem)
我之前曾嘗試將我的 HttpGets 的返回類型交換為我的對象類型",并且響應是我的對象的 ToString() 方法的 json 表示...這讓我知道序列化沒有通過我的轉換器.
I had previously tried to swap the return type of my HttpGets to "my object type" and the response was a json representation of my object's ToString() method...which let me know that serialization was not passing through my converters.
將我的 HttpGets 的返回類型從字符串更改為我的對象類型"并將這些轉換器直接插入 WebAPi 的默認 HttpConfiguration 就可以了.
Changing the return type of my HttpGets from string to "my object type" and plugging those converters straight into WebAPi's default HttpConfiguration did the trick.
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new FooConverter());
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new BarConverter());
簡單易懂.
推薦答案
你可能有這樣的情況:
public string GetFoobars()
{
var foobars = ...
return JsonConvert.SerializeObject(foobars);
}
在這種情況下,您將使用 Json.NET 將對象序列化為字符串,然后通過將結果作為字符串返回,API 控制器會將字符串序列化為 JavaScript 字符串文字——這將導致字符串被包裝在雙引號中并導致字符串中的任何其他特殊字符用反斜杠轉義.
In this case, you're serializing the object into string with Json.NET, then by returning the result as a string, the API controller will serialize the string as a JavaScript string literal—which will cause the string to be wrapped in double quotes and cause any other special characters inside the string to escaped with a backslash.
解決方案是簡單地自己返回對象:
The solution is to simply return the objects by themselves:
public IEnumerable<Foobar> GetFoobars()
{
var foobars = ...
return foobars;
}
這將導致 API 控制器使用其默認設置序列化對象,這意味著它將根據從客戶端傳入的參數將結果序列化為 XML 或 JSON.
This will cause the API controller to serialize the objects using it's default settings, meaning it will serialize the result as XML or JSON depending on the parameters passed in from the client.
進一步閱讀
- ASP.NET Web 中的 JSON 和 XML 序列化API
這篇關于JSON.NET Parser *似乎*對我的對象進行雙重序列化的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!