我有数据模型类,我正在将其序列化为JSON,以便能够将序列化的JSON发布到Web服务。数据模型如下所示:
using Newtonsoft.Json;
namespace WebCrawler.Models {
[JsonObject(MemberSerialization.OptIn)]
public class LinkDataViewModel
{
[JsonProperty]
public string Title { get; set; }
.....
[JsonProperty]
public string CustomerID { get; set; }
}
}
我应该如何更改要序列化的数据模型类 JSON 如下所示:
{"PostPropertyRequest": {SerializedDataModel}}
你可以用这种方式编写你的自定义json(让你的类派生自JsonConverter并覆盖3个方法(
using Newtonsoft.Json;
namespace WebCrawler.Models {
[JsonObject(MemberSerialization.OptIn)]
public class LinkDataViewModel : JsonConverter
{
[JsonProperty]
public string Title { get; set; }
.....
[JsonProperty]
public string CustomerID { get; set; }
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 == null)
{
serializer.Serialize(writer, null);
return;
}
var properties = value.GetType().GetProperties();
writer.WriteStartObject();
//your custom property
writer.WritePropertyName("PostPropertyRequest");
writer.WriteStartObject();
foreach (var property in properties)
{
// write property name
writer.WritePropertyName(property.Name);
serializer.Serialize(writer, property.GetValue(value, null));
}
writer.WriteEndObject();
writer.WriteEndObject();
}
}
}
有关文档,请参阅这篇不错的文章
对于 Json,重要的是要了解与 XML 不同,它没有根元素,您当前的 Json 生成是:
{
"Title": "Value",
"CustomerID": "Value"
}
您需要的是:
{
"PostPropertyRequest":
{
"Title": "Value",
"CustomerID": "Value"
}
}
您只需包装当前类,应用 Json 属性并序列化:
[JsonObject(MemberSerialization.OptIn)]
public class LinkDataViewModelWrapper
{
[JsonProperty("PostPropertyRequest")]
public LinkDataViewModel LinkDataViewObj{ get; set; }
}
现在你需要序列化 LinkDataViewModelWrapper,在初始化各种元素和属性之后
[JsonObject(MemberSerialization.OptIn)]
public class MyModel
{
[JsonProperty]
public LinkDataViewModel PostPropertyRequest{ get; set; }
}
创建上面的模型并将其序列化。
MyModel model = new MyModel();
model.PostPropertyRequest = your model.
现在序列化模型。