我正在尝试使用JSON.net为类编写转换器
当我序列化JsonObject
类型的对象时,我得到以下输出
{"DataObject":{"id":"1","name":"data name"}}
如何将DataObject
一级移动以获得以下输出:
{"id":"1","name":"data name"}
您可以在下面找到相关代码。
我的课程格式如下:
public class JsonObject
{
public JsonObject(IDataObject dataObject)
{
this.DataObject= dataObject;
}
[JsonConverter(typeof(JsonDataObjectConverter))]
public IDataObject DataObject;
}
DataObject
有一些属性:
public class MyDataObject : IDataObject
{
[JsonProperty(PropertyName = "id", Required = Required.Always)]
public string Id { get; set; }
[JsonProperty(PropertyName = "name", Required = Required.Always)]
public string Name { get; set; }
}
我从文档中提到this page并编写了以下转换器:
public class JsonDataObjectConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(IDataObject).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
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 is MyDataObject dataObject)
{
writer.WriteStartObject();
writer.WritePropertyName("id");
writer.WriteValue(dataObject.Id);
writer.WritePropertyName("name");
writer.WriteValue(dataObject.Name);
writer.WriteEndObject();
}
}
}
感谢任何帮助。谢谢。
答案 0 :(得分:0)
通过将转换器移动到类而不是属性并使用[JsonIgnore]
忽略属性,我能够获得所需的输出。该属性需要被忽略,因为该类的转换器将为该属性生成JSON,如下所示。
所以JsonObject
类将是:
[JsonConverter(typeof(JsonObjectConverter))]
public class JsonObject
{
public JsonObject(IDataObject dataObject)
{
this.DataObject= dataObject;
}
[JsonIgnore]
public IDataObject DataObject;
}
然后像这样创建转换器:
public class JsonObjectConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(IDataObject).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
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)
{
JsonObject jsonObject = (JsonObject)value;
if (jsonObject.DataObject.GetType() == typeof(MyDataObject))
{
MyDataObject dataObject = (MyDataObject) jsonObject.DataObject;
writer.WriteStartObject();
writer.WritePropertyName("id");
writer.WriteValue(dataObject.Id);
writer.WritePropertyName("name");
writer.WriteValue(dataObject.Name);
writer.WriteEndObject();
}
}
}
这给出了所需的输出:
{"id":"1","name":"data name"}