1. 程式人生 > >JSON.NET Error Self referencing loop detected for type

JSON.NET Error Self referencing loop detected for type

我們在使用JsonConvert.SerializeObject 把物件轉換為json格式出現以下錯誤

其他資訊: Self referencing loop detected for property

解決辦法如下:

Use JsonSerializerSettings

  • ReferenceLoopHandling.Error (default) will error if a reference loop is encountered. This is why you get an exception.
  • ReferenceLoopHandling.Serialize is useful if objects are nested but not indefinitely.
  • ReferenceLoopHandling.Ignore will not serialize an object if it is a child object of itself.

Example:

JsonConvert.SerializeObject(YourPOCOHere,Formatting.Indented,newJsonSerializerSettings{ReferenceLoopHandling=ReferenceLoopHandling.Serialize});

Should you have to serialize an object that is nested indefinitely you can use

PreserveObjectReferences to avoid a StackOverflowException.

Example:

JsonConvert.SerializeObject(YourPOCOHere,Formatting.Indented,newJsonSerializerSettings{PreserveReferencesHandling=PreserveReferencesHandling.Objects});

MVC4解決如下:

json.net serializer supports to ignore circular reference on global setting. A quick fix is to put following code inWebApiConfig.cs

file:

 config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling=Newtonsoft.Json.ReferenceLoopHandling.Ignore;

The simple fix will make serializer to ignore the reference which will cause a loop. However, it has limitations:

The data loses the looping reference information The fix only applies to JSON.net The level of references can't be controlled if there is a deep reference chain Fix 2: Preserving circular reference globally

This second fix is similar to the first. Just change the code to:

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling=Newtonsoft.Json.ReferenceLoopHandling.Serialize;     
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling=Newtonsoft.Json.PreserveReferencesHandling.Objects;

The data shape will be changed after applying this setting.

[{"$id":"1","Category":{"$id":"2","Products":[{"$id":"3","Category":{"$ref":"2"},"Id":2,"Name":"Yogurt"},{"$ref":"1"}],"Id":1,"Name":"Diary"},"Id":1,"Name":"Whole Milk"},{"$ref":"3"}]

The $id and $ref keeps the all the references and makes the object graph level flat, but the client code needs to know the shape change to consume the data and it only applies to JSON.NET serializer as well.

Fix 3: Ignore and preserve reference attributes

This fix is decorate attributes on model class to control the serialization behavior on model or property level. To ignore the property:

1:publicclassCategory2:{3:publicintId{get;set;}4:publicstringName{get;set;}5:6:[JsonIgnore]7:[IgnoreDataMember]8:publicvirtualICollection<Product>Products{get;set;}9:}

JsonIgnore is for JSON.NET and IgnoreDataMember is for XmlDCSerializer. To preserve reference:

1:// Fix 3 2:[JsonObject(IsReference=true)]3:publicclassCategory4:{5:publicintId{get;set;}6:publicstringName{get;set;}7:8:// Fix 3 9://[JsonIgnore] 10://[IgnoreDataMember] 11:publicvirtualICollection<Product>Products{get;set;}12:}13:14:[DataContract(IsReference=true)]15:publicclassProduct16:{17:[Key]18:publicintId{get;set;}19:20:[DataMember]21:publicstringName{get;set;}22:23:[DataMember]24:publicvirtualCategoryCategory{get;set;}25:}

JsonObject(IsReference = true)]is for JSON.NET and [DataContract(IsReference = true)] is for XmlDCSerializer. Note that: after applyingDataContract on class, you need to add DataMember to properties that you want to serialize.

 

相關推薦

JSON.NET Error Self referencing loop detected for type

我們在使用JsonConvert.SerializeObject 把物件轉換為json格式出現以下錯誤 其他資訊: Self referencing loop detected for property 解決辦法如下: Use JsonSerializerSettin

c# json 序列化時遇到錯誤 error Self referencing loop detected for type

red elf 錯誤 serial bject cin nbsp for serialize 參考網址:http://blog.csdn.net/adenfeng/article/details/41622255   在寫redis緩存幫助類的時候遇到的這個問題,本來打算

JSON.NETSelf referencing loop detected with type的原因以及解決辦法

從數據 xml序列化器 信息 不起作用 hand href creat server HR 模型中有循環引用是很常見的。例如,以下模型顯示雙向導航屬性: 1: public class Category 2: { 3: public Cate

EF關於報錯Self referencing loop detected with type的原因以及解決辦法

content handle check new ren calc and cal str 1)具體報錯 { "Message": "出現錯誤。", "ExceptionMessage": "“ObjectContent`1”類型未能序列化內容類型“app

JSON parse error: No suitable constructor found for type

fas obj error: https not in error ror ppi port 錯誤信息: 2019-02-19 09:17:58,678 [http-nio-8080-exec-1] WARN org.springframework.web.servlet.

解決 Error:Unable to find encoder for type stored in a Dataset

Error: Unable to find encoder for type stored in a Dataset.  Primitive types (Int, String, etc) and Product t

error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value '

網路上看到各種解決辦法,但是我的原因是添加了多餘的庫。 在 配置裡將如下庫除去解決了問題,實際上,opencv3.0的配置變的很簡單,只要加這兩個庫即可 opencv_ts300d.lib opencv_world300d.lib 這些庫不必新增。 IlmImfd.

Error LNK2038 mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value

場景:用Jsoncpp原始碼編譯生成的庫(lib),與程式一起使用時,vs輸出錯誤提示Error LNK2038; A1:原因:需要使用的是靜態庫,而實際的庫是動態庫。         解決:將動態庫

MYSQL: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

tar new ica host star init upd pass skip 1) /etc/init.d/mysqld stop2) mysqld_safe --skip-grant-tables &3) mysql -u root4) Setup new M

WEB.NET error:請添加一個名為 jquery (區分大小寫)的 ScriptResourceMapping 解決方案

clas resource 文件 全局 區分大小寫 get com 技術 star 參考 http://blog.csdn.net/kisscatforever/article/details/50579935 今天用了一個組件 一個驗證型的組件。 然後出現了這個問

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'mysql'

centos 解決 ice 個數 oca 用戶 acc 登錄 use 在centos下安裝好了mysql,用root帳號連上mysql,然後創建一個數據庫,提示下圖錯誤:   提示:ERROR 1044 (42000): Access denied for user [e

MySQL Error: Illegal mix of collations for operation 'concat'

img err style for utf8 size ron 字段 png   在使用concat連接字符串時出現錯誤:MySQL Error: Illegal mix of collations for operation ‘concat‘   原因:字段操作默認為UT

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

註釋 .cn tables table 數據 mysql數據庫 using ice 登錄 解決: (1)修改my.cnf中[mysqld]中增加skip-grant-tables (2)重啟mysql數據庫:service mysqld restart (3)無密碼登錄my

Json.net實現方便的Json轉C#(dynamic動態類型)對象

bar 方便 api lba c# oid tool 可能 情況 以前需要將一段json字符串轉換為C#對象時,一般都是定義一個與之對應的實體類來接收。這樣做有一個很大的缺點,就是當字符串特別長,屬性特別多,又有嵌套時,手敲這個實體類就非常痛苦。 比如之前做的一個接收百度七

關於JSON類的兩個用途與for..in和for循環的區別

進行 length 區別 prop per str 字符 number stringify JSON 這個類的兩個用途: 1)將Object 對象,轉換成string 類型 var obj = {"a":"1","b":"2","c":"json"}; var

使用Json.NET來序列化所需的數據

toolbar src 關鍵字 boolean 自定義 ember api log mar 我們在做開發的時候,很多時候需要和Json數據格式打交道,如Web開發裏面,很多時候,數據通過Json進行傳遞到頁面上,然後在進行處理的。而使用Json的時候,我們很多時候會涉及到幾

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

mage ron 打開 技術分享 -1 密碼 logs erro password ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: NO) 問題: 解

基於.NET CORE微服務框架 -談談surging 的messagepack、protobuffer、json.net 序列化

ces type posit rep factor bsp 技術分享 https 我們 1、前言 surging內部使用的是高性能RPC遠程服務調用,如果用json.net序列化肯定性能上達不到最優,所以後面擴展了protobuf,messagepack序列化組件

.NET Core protobuf-net、MessagePack、Json.NET序列化/反序列化性能測試

img alt int 序列化 james 最優 5.1 out mar 測試代碼Zonciu/SerializationTest.cs, 源自neuecc/ZeroFormatterBenchmark.cs。 NuGet包及其版本 mgravell/protobuf-ne

ERROR 1045 (28000): Access denied for user 'root'@'localhost'

plain set tables mys res div ror localhost number #1.停止mysql數據庫 /etc/init.d/mysqld stop #2.執行如下命令 mysqld_safe --user=mysql --skip-grant