使用Web API和JSON.NET序列化对象时防止$ id / $ ref

麦可

我似乎无法阻止Newtonsoft.Json.PreserveReferencesHandling.Objects在序列化对象时使用Web API / JSON.NET 换句话说,尽管使用以下设置,但始终在序列化对象中使用$ id / $ ref:

public class MvcApplication : System.Web.HttpApplication {

    protected void Application_Start () {
        WebApiConfig.Register(GlobalConfiguration.Configuration);
    }

}

public static class WebApiConfig {

    public static void Register (HttpConfiguration config) {
        JsonMediaTypeFormatter jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().Single();
        jsonFormatter.UseDataContractJsonSerializer = false;
        jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
        jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
    }

}

有任何想法吗?

麦可

如果在对象(例如DataContract)上使用序列化属性,请参阅JSON.Net文档中有关序列化属性的内容

除了使用内置的Json.NET属性外,Json.NET还将查找[SerializableAttribute] [2](如果DefaultContractResolver上的IgnoreSerializableAttribute设置为false)[DataContractAttribute] [3],[DataMemberAttribute] [4]和[NonSerializedAttribute] [5] ...在确定如何序列化和反序列化JSON时。

它还说:

笔记

Json.NET属性优先于标准.NET序列化属性,例如,如果属性中同时存在JsonPropertyAttribute和DataMemberAttribute并自定义名称,则将使用JsonPropertyAttribute的名称。

看来解决问题的方法是[JsonObject(IsReference = false)]像这样添加到您的对象中:

[DataContract(IsReference = true)]
[JsonObject(IsReference = false)]
public class MyObject
{
    [DataMember]
    public int MyProperty { get; set; }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用JSON序列化程序反序列化Mongo DB对象ID

如何JSON在Java中反序列化时,它包含Json.Net C#$产生ref和$ ID

使用json.net对对象属性进行条件序列化/反序列化

使用JSON.net反序列化对象

使用Json.NET序列化对象列表

当我使用fastapi和pydantic构建POST API时,出现TypeError:类型为JSON的对象无法序列化

无法使用 jackson 反序列化包含 2 个具有相同 ID 的对象的 Json

使用Spring Hateoas的jackson和Jackson2HalModule反序列化json时的null id属性

我的Web API C#.net服务器无法反序列化JSON对象

使用C#和Json.NET根据条件序列化JSON对象

Web API未收到序列化对象的json

使用值对象作为实体ID时自定义Jackson序列化

使用JSON.NET序列化复杂字典时,更改“键”和“值”的名称

如何使用活动模型序列化程序自定义json-api序列化模型的ID?

序列化和反序列化使用Protobuf-net实现抽象类的对象

反序列化JSON数组使用Jackson和Web客户端对象

使用Java和Jersey使用类别ID作为键的类别的JSON反序列化

使用单独的列表和对象序列化 Json 文件

反序列化和使用JSON对象

如何使用JSON序列化对象

使用Alamofire序列化JSON对象

使用json和python序列化/反序列化对象列表

从ID到对象的JSON反序列化

TypeError 对象 ID 不是 JSON 可序列化的

如何使用Json.net在Vb.net中反序列化JSON对象?

使用 JSON.NET 反序列化和序列化字典<string, object>

无法使用Json序列化Web API中的响应

在C#Web Api中反序列化JSON对象时,如何绑定给定属性?

Django REST API。如何使用用户ID序列化ArrayField,并作为User模型的JSON对象进行检索?