2012-11-05 46 views
1

假設我有這樣轉換實體框架對象JSON(無對象圖)

Library 1 ---- 1+ Book 1 ---- 1+ Page 

我想序列一本書的JSON對象與頁面對象數組的對象結構。

使用JSON.net序列化程序,我可以在沒有獲得循環引用的情況下將其序列化,但JSON仍然在每個頁面中包含該書的所有屬性,其中包括有關該庫的數據......其他書上的數據是一大堆噪音。

從這個問題的答案 - Serialize Entity Framework objects into JSON,我知道我可以做泛型,但這真的是唯一的方法嗎?這看起來像是一大堆額外的工作。特別是如果對於Json結果是Book和其中的頁面對象數組。

我使用實體框架4.3.1和Json.net 4.0.30319 ...

回答

3

你應該看看serialization attributes

[JsonObject(MemberSerialization.OptIn)] 
public class Page 
{ 
    [JsonProperty] 
    public string Text { get; set; } 

    // not serialized because mode is opt-in 
    public Book Book { get; set; } 
} 

原來的答覆

上述方式在多數的情況下中將優先選擇,但也有一些地方是不夠的。

有兩種方法可以做到這一點。

您可以實現JsonConverter,並覆蓋WriteJson方法以僅寫入所需的屬性。

class BookConverter : JsonConverter 
{ 
    public override bool CanConvert(Type objectType) 
    { 
     return objectType == typeof(Book); 
    } 

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
    { 
     throw new NotImplementedException(); 
    } 

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
    { 
     if (value.GetType() == typeof(T2)) 
     { 
      JObject obj = new JObject(); 
      Book b = value as Book; 
      obj["titre"] = b.Name; 
      obj["pages"] = b.Pages; 
      // This line can also be 
      // obj.WriteTo(writer, this); 
      // if you also need change the way pages are serialized. 
      obj.WriteTo(writer, null); 
     } 
     else 
     { 
      throw new NotImplementedException(); 
     } 
    } 
} 

你可以把它像:

string result = JsonConvert.SerializeObject(
    book, 
    new JsonSerializerSettings 
    { 
     Converters = new JsonConverter[] { new BookConverter() } 
    }); 

你還可以創建一個JsonBook類和序列化。

class JsonBook{ 
    public JsonBook(Book b){/*...*/} 
    public List<Pages> l; 
    public string title; 
    // No reference to Library. 
} 
+0

我剛回來看看這個答案,這是一個很好的答案! –