你應該看看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.
}
我剛回來看看這個答案,這是一個很好的答案! –