【发布时间】:2013-10-11 01:48:13
【问题描述】:
我将 ASP.NET MVC 应用程序切换为使用 Newtonsoft JsonSerializer 进行 JSON 序列化,如下所示:
var writer = new JsonTextWriter(HttpContext.Response.Output) { Formatting = Formatting };
var serializer = JsonSerializer.Create();
serializer.Serialize(writer, myData);
这会生成一些具有 $id 和 $ref 属性的 JSON,然后从 JSON 中删除重复的对象。我知道这是一个很棒的功能,但是读取此 JSON 的客户端无法支持解释这些引用并期望完整的对象存在。我尝试将JsonSerializerSettings 上的PreserveReferencesHandling 属性设置为每个可能的值,但似乎没有任何区别。
如何禁用 $id 和 $ref 属性的创建并让 Newtonsoft 序列化程序写出整个对象图?
编辑:这是一个示例 C# 类、我期望的 JSON,以及由 Newtonsoft 序列化程序创建的 JSON:
public class Product
{
public Image MainImage { get; set; }
public List<Image> AllImages { get; set; }
}
public class Image
{
public int Id { get; set; }
public string Url { get; set; }
}
我期望的 JSON:
{
MainImage: { Id: 1, Url: 'http://contoso.com/product.png' },
AllImages: [{ Id: 1, Url: 'http://contoso.com/product.png' },{ Id: 2, Url: 'http://contoso.com/product2.png' }]
}
由 Newtonsoft 序列化程序创建的 JSON(注意 MainImage 中添加的 $id 参数和被 $ref 参数完全替换的引用对象):
{
MainImage: { $id: 1, Id: 1, Url: 'http://contoso.com/product.png' },
AllImages: [{ $ref: 1 },{ Id: 2, Url: 'http://contoso.com/product2.png' }]
}
我知道 Newtonsoft 版本更好(它是 DRYer),但读取此 JSON 输出的客户端不理解 $ref 的含义。
【问题讨论】:
-
如果您发布了一些代表您尝试序列化的内容的示例数据以及所需的 JSON 输出,将会很有帮助。
-
@BrianRogers 我已编辑以包含示例代码和数据。
-
您使用的是哪个 Newtonsoft 版本?因为在一个版本为 5.0.6 的空项目中,我得到了没有 $id 和 $ref 的预期结果...