[英]How to serialize an object to a JSON string property instead of an object using Json.Net
我有以下類結構。 我想要實現的是代替Bar
序列化為JSON中的對象,使用其內部屬性Name
值序列化為字符串並忽略Id
屬性。 我沒有需要反序列化它的場景,但是我必須從數據庫加載Bar
對象和其他屬性並進行一些內部操作但不使用它進行傳輸。
class Foo
{
[JsonProperty("bar")]
public Bar Bar { get; set; }
}
class Bar
{
[JsonIgnore]
public Guid Id { get; set; }
[JsonProperty]
public string Name { get; set; }
}
預期的JSON:
{
bar: "test"
}
使用自定義JsonConverter
,您可以控制轉換以輸出您想要的任何內容。
就像是:
public class BarConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Bar);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var bar = value as Bar;
serializer.Serialize(writer, bar.Name);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Note: if you need to read to, you'll need to implement that here too
// otherwise just throw a NotImplementException and override `CanRead` to return false
throw new NotImplementedException();
}
}
然后你可以使用JsonConverterAttribute
來裝飾你的屬性或Bar
類(取決於你是否總是希望Bar
像這樣序列化,或者僅用於此屬性):
[JsonConverter(typeof(BarConverter))]
public Bar Bar { get; set; }
要么:
[JsonConverter(typeof(BarConverter))]
public class Bar
另一種“快速而骯臟”的方法是只有一個將被序列化的shadow屬性:
public class Foo
{
[JsonProperty("bar")] // this will be serialized as "bar"
public string BarName
{
get { return Bar.Name; }
}
[JsonIgnore] // this won't be serialized
public Bar Bar { get; set; }
}
請注意,如果您希望能夠閱讀,那么您還需要提供一個setter,並找出如何將字符串名稱轉換回Bar
實例。 這就是快速和骯臟的解決方案有點不愉快的地方,因為你沒有一種簡單的方法來限制在反序列化期間將BarName
設置為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.