2014-01-10 34 views
14

在序列化對象時,我似乎無法阻止Web API/JSON.NET使用Newtonsoft.Json.PreserveReferencesHandling.Objects

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; 
    } 

} 

任何想法:換句話說,$ ID/$裁判總是在序列化的對象,儘管使用以下設置使用?

+0

在''WebApiConfig''類(''公共靜態無效的寄存器設置這個( HttpConfiguration config)從Global.asax.cs中的''protected void Application_Start()''調用 – Michael

+1

根據@AndreHaverdings'下面的答案,將PreserveReferencesHandling設置爲All將導致添加ID和引用 設置最後一個line to 'jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveRef erencesHandling.None;' 應該做的伎倆。 – Buzzwig

回答

3

如果你的對象(如DataContract)使用序列化的屬性,從JSON.Net documentation on Serialization Attributes

除了使用內置的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)]到你的對象(S)是這樣的:

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

下面是一些JavaScript我使用來處理在客戶端中的$ id/$參考對象:

// function to return a JSON object form a JSON.NET serialized object with $id/$ref key-values 
// obj: the obj of interest. 
// parentObj: the top level object containing all child objects as serialized by JSON.NET. 
function getJsonNetObject(obj, parentObj) { 
    // check if obj has $id key. 
    var objId = obj["$id"]; 
    if (typeof (objId) !== "undefined" && objId != null) { 
     // $id key exists, so you have the actual object... return it 
     return obj; 
    } 
    // $id did not exist, so check if $ref key exists. 
    objId = obj["$ref"]; 
    if (typeof (objId) !== "undefined" && objId != null) { 
     // $ref exists, we need to get the actual object by searching the parent object for $id 
     return getJsonNetObjectById(parentObj, objId); 
    } 
    // $id and $ref did not exist... return null 
    return null; 
} 

// function to return a JSON object by $id 
// parentObj: the top level object containing all child objects as serialized by JSON.NET. 
// id: the $id value of interest 
function getJsonNetObjectById(parentObj, id) { 
    // check if $id key exists. 
    var objId = parentObj["$id"]; 
    if (typeof (objId) !== "undefined" && objId != null && objId == id) { 
     // $id key exists, and the id matches the id of interest, so you have the object... return it 
     return parentObj; 
    } 
    for (var i in parentObj) { 
     if (typeof (parentObj[i]) == "object" && parentObj[i] != null) { 
      //going one step down in the object tree 
      var result = getJsonNetObjectById(parentObj[i], id); 
      if (result != null) { 
       // return found object 
       return result; 
      } 
     } 
    } 
    return null; 
} 
+0

感謝您的答案,實際工作。我花了最後的半小時嘗試在Microsoft WebApi 2.1中關閉此功能。 – ChrisG

23

將這個在Global.asax配置參考處理。 PreserveReferencesHandling不應該是'全部'

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None; 
+0

我嘗試過所有PreserveReferencesHandling組合,包括「無」。每個設置(當前爲「無」)都會產生相同的輸出:輸出$ id/$ ref。某處,某處必定會壓倒我的設置。 – Michael

+0

@Michael你能解決這個錯誤嗎?你能幫我關於這個話題:http://stackoverflow.com/questions/41244296/net-webapi-how-to-prevent-ref-x-output-of-json – fobus

-2

[JsonIgnore]爲我工作。在模型中,包括:

[JsonIgnore] 
    public virtual ICollection<cell_order> cell_order { get; set; } 

不幸的是,這必須在需要的情況下針對每種情況進行。

相關問題