【发布时间】:2015-11-04 14:26:57
【问题描述】:
我正在使用自定义 JsonConverter(CustomInfoConverter) 对正在解析的每个自定义点网类型(CustomType) 进行一些操作。
下面是自定义JsonConverter的代码:
public class CustomInfoConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(CustomType);
}
public override bool CanRead
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return true;
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var customType = (CustomType)value;
if (customType == null || null== customType.TimeZone) return;
//DateTime currentDateTime = customType.Date??DateTime.Now;
DateTime currentDateTime = DateTime.SpecifyKind(customType.Date ?? DateTime.Now, DateTimeKind.Unspecified);
DateTime userDateTime = TimeZoneInfo.ConvertTimeFromUtc(currentDateTime, customType.TimeZone);
customType.Date = userDateTime;
writer.WriteValue(JsonConvert.SerializeObject(customType) );
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
我在这里面临的问题是额外的字符'\' 被附加到这里,所以我的回复看起来像JsonConvert.SerializeObject(customType) 正在序列化 customType 对象,而默认序列化程序正在序列化它(如果我错了,请纠正我)。有什么办法解决这个问题?
{
"Data": [
{
"Type": "someThing",
"Created": "{\"Date\":\"2015-11-05T01:09:21.6721171+05:30\",\"User\":{\"Upn\":\"james\",\"FirstName\":\"James\",\"LastName\":\"Johnson\",\"Id\":\"69cb471e-da83-48c3-8f60-d1bb29d41177\",\"Name\":\"Johnson\"},\"TimeZone\":{\"Id\":\"India Standard Time\",\"DisplayName\":\"(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi\",\"StandardName\":\"India Standard Time\",\"DaylightName\":\"India Daylight Time\",\"BaseUtcOffset\":\"05:30:00\",\"AdjustmentRules\":null,\"SupportsDaylightSavingTime\":false},\"Latitude\":null,\"Longitude\":null}",
}
],
}
从here了解到,可能是因为re-json-ing, 那么,解决这个问题的方法是什么?
【问题讨论】:
-
你能给 json 提供额外的 '\',你的字符串看起来很好,除了最后缺少 ",是你的错误输入还是这正是你的 json(那时它不起作用全部)?
-
用完整的 json 响应编辑了问题
标签: c# json serialization json.net