JSON.NET 解析器 * 似乎 * 是双重序列化我的对象 [英] JSON.NET Parser *seems* to be double serializing my objects

查看:17
本文介绍了JSON.NET 解析器 * 似乎 * 是双重序列化我的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是:

这是从我的 WebAPI 控制器发回的响应.

This is the response being sent back from my WebAPI controller.

"[
   [
      {"id":"identifier"},
      {"name":"foobar"}
   ]
]"

请注意,响应包含在引号中,并且所有嵌入的引号都已转义.这显然是一个问题.我可以为 JSON.NET Serializer 提供任何设置来防止这种情况发生吗?

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.

进一步阅读

这篇关于JSON.NET 解析器 * 似乎 * 是双重序列化我的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆