使用代码......
[Test]
public void test()
{
var entity = new Foo();
var json = Newtonsoft.Json.JsonConvert.SerializeObject(entity);
}
针对以下琐碎的班级结构...
public class Foo
{
public Foo() { FooDate = new DateTimeWrapper(); }
public DateTimeWrapper FooDate { get; set; }
}
public class DateTimeWrapper
{
public DateTimeWrapper() { DateTime = DateTime.Now; }
public DateTime DateTime { get; set; }
}
...将json变量设置为...
{"FooDate":{"DateTime":"2013-08-30T13:36:15.4862093-05:00"}}
我想要返回的JSON是......
{"FooDate":"2013-08-30T13:36:15.4862093-05:00"}
没有嵌入的DateTime部分。如何使用JSON.net序列化为此自定义JSON,然后将上述字符串反序列化为原始对象?
修改
我知道可以简化对象结构以产生所需的输出。但是,我想用给定的对象结构生成输出。此代码已归结为突出显示该问题。我没有把所有代码都写下来,也没有对它进行冗长的解释b / c它与问题无关。
答案 0 :(得分:3)
正如我在评论中所说,可以通过创建自定义 JsonConverter
轻松完成var entity = new Foo();
var json = JsonConvert.SerializeObject(entity, new DateTimeWrapperConverter());
public class DateTimeWrapperConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTimeWrapper);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
//Left as an exercise to the reader :)
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var obj = value as DateTimeWrapper;
serializer.Serialize(writer, obj.DateTime);
}
}