- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我们以一种奇怪的格式从 API 获取序列化的 DateTimes:/Date(1574487012797)/
为了使用 System.Text.Json
反序列化这个值,我们编写了自己的 JsonConverter
:
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var dateTimeString = reader.GetString();
dateTimeString = dateTimeString.Replace("/Date(", "");
dateTimeString = dateTimeString.Replace(")/", "");
var epoch = Convert.ToInt64(dateTimeString);
var dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(epoch);
return dateTimeOffset.UtcDateTime;
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"));
}
}
我想为此转换器编写单元测试。我尝试的是以下内容:
public class DateTimeConverterTest
{
private readonly DateTimeConverter testee;
public DateTimeConverterTest()
{
this.testee = new DateTimeConverter();
}
[Fact]
public void Read_WhenCalledWithSerializedDateTime_ThenReturnDeserializedDateTime()
{
var a = "{\r\n \"PublikationsDatum\": \"/Date(1573581177000)/\" \r\n}";
//var serializedDateTime = "/Date(1573581177000)/";
var utf8JsonReader = new Utf8JsonReader(Encoding.UTF8.GetBytes(a), false, new JsonReaderState(new JsonReaderOptions()));
//utf8JsonReader.TokenType = JsonTokenType.String;
var deserializedDateTime = this.testee.Read(ref utf8JsonReader, typeof(DateTime), new JsonSerializerOptions {IgnoreNullValues = true});
}
private class TestClass
{
public DateTime PublikationsDatum { get; set; }
}
}
不幸的是,在尝试执行单元测试时,我在 var dateTimeString = reader.GetString();
InvalidOperationException
System.InvalidOperationException: 'Cannot get the value of a token type 'None' as a string.'
如何正确设置测试/我做错了什么?
最佳答案
在调用 JsonConverter<T>.Read()
之前,您必须将 Utf8JsonReader
向前移动,直到它位于"PublikationsDatum"
属性的值上,例如像这样:
public void Read_WhenCalledWithSerializedDateTime_ThenReturnDeserializedDateTime()
{
var a = "{\r\n \"PublikationsDatum\": \"/Date(1573581177000)/\" \r\n}";
var utf8JsonReader = new Utf8JsonReader(Encoding.UTF8.GetBytes(a), false, new JsonReaderState(new JsonReaderOptions()));
while (utf8JsonReader.Read())
if (utf8JsonReader.TokenType == JsonTokenType.String)
break;
var deserializedDateTime = this.testee.Read(ref utf8JsonReader, typeof(DateTime), new JsonSerializerOptions {IgnoreNullValues = true});
}
演示 fiddle #1 here。
或者,您可以通过解析简单的 JSON 字符串文字"/Date(1573581177000)/"
来简化单元测试。但是,您仍然需要将阅读器推进一次,因为它最初位于第一个标记的开头之前,即utf8JsonReader.TokenType == JsonTokenType.None
:
public void Read_WhenCalledWithSerializedDateTime_ThenReturnDeserializedDateTime()
{
var a = "\"/Date(1573581177000)/\"";
var utf8JsonReader = new Utf8JsonReader(Encoding.UTF8.GetBytes(a), false, new JsonReaderState(new JsonReaderOptions()));
// Reader always starts out without having read anything yet, so TokenType == JsonTokenType.None initially
Assert.IsTrue(utf8JsonReader.TokenType == JsonTokenType.None);
utf8JsonReader.Read();
var deserializedDateTime = this.testee.Read(ref utf8JsonReader, typeof(DateTime), new JsonSerializerOptions {IgnoreNullValues = true});
}
演示 fiddle #2 here。
注意事项:
"\/Date(number of ticks)\/"
是微软最初的JavaScriptSerializer
用于将DateTime
序列化为JSON字符串的格式。详情请参阅the documentation remarks。(在 JSON string literal 中,\/
只是一个转义的 \
并将被 Utf8JsonReader
默默地解释为这样,参见 fiddle #3 here 。你不需要检查\/
在您的 JSON 转换器中处理JavaScriptSerializer
生成的日期和时间。)
DataContractSerializer
使用了稍微不同的格式。来自docs:
DateTime values appear as JSON strings in the form of "/Date(700000+0500)/", where the first number (700000 in the example provided) is the number of milliseconds in the GMT time zone, regular (non-daylight savings) time since midnight, January 1, 1970. The number may be negative to represent earlier times. The part that consists of "+0500" in the example is optional and indicates that the time is of the Local kind - that is, should be converted to the local time zone on deserialization. If it is absent, the time is deserialized as Utc. The actual number ("0500" in this example) and its sign (+ or -) are ignored.
Newtonsoft 对 DateTimeUtils.TryParseDateTimeMicrosoft()
的实现可能有助于指导您的实现。
关于c# - 测试自定义 JsonConverter 时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59028159/
编辑:澄清问题: 我已经覆盖了基类型的 JsonConverter(通过将 [JsonConverter(typeof(TConverter))] 应用于父类(super class)),但是当直接反
尝试使用 JsonConvert.PopulateObject 更新类属性时,未调用 JsonPathConverter,因此未完成填充。 示例类: [JsonConverter(typeof(Jso
我有一个我不能改变的类: public enum MyEnum { Item1 = 0, Item2 = 1 } public class foo { [JsonConvert
我正在使用 Json.NET (6.0.3) 进行序列化。我编写了一个自定义 JsonConverter TestConverter 来处理一些 BaseClass 的实例(通过将它们转换为整数 id
我有一个要求,我需要将默认值设置为下面的复杂属性 Instances使用 JsonProperty和 DefaultValue . 我知道我们可以为以下链接中提到的原始属性实现这一点,但需要知道我们如
我尝试查找上述比较,但找不到答案。 因为有多种方法可以获取 JObject(或所有继承自 JToken 的子类型)例如: Method1 . JObject.FromObject(obj); Meth
我已启用我的 API 以使用字符串值序列化/反序列化枚举。为此,我已将 JsonStringEnumConverter 添加到 API 的 Startup 类中受支持的 JsonConverter 列
我有一个 Employee 类,其中 Manager 属性本身是 Employee 类型 public class Employee { public string FirstName { g
我已经卡住模型(简化): part 'initial_data_model.freezed.dart'; part 'initial_data_model.g.dart'; @freezed clas
我正在尝试将两个字段和一个包含两个字段的捆绑对象发布到 Mailchimp 的 API 端点。 var store_id = ConfigurationManager.AppS
以下VB.NET代码使用Newtonsoft JSON.NET库,并在按钮单击事件处理程序中执行并阻止UI线程: Dim table As DataTable = Await Task.Factory
我遇到了一个问题,其中以下 ToJson() 方法返回的字符串仅为“{}” public class GenericRequest { publ
这个问题在这里已经有了答案: JSON Can't be Deserialized to Object, Needs Array? (2 个答案) 关闭 9 年前。 我有这个 Json 返回: [
我遇到了一个问题,其中以下 ToJson() 方法返回的字符串仅为“{}” public class GenericRequest { publ
这个问题在这里已经有了答案: JSON Can't be Deserialized to Object, Needs Array? (2 个答案) 关闭 9 年前。 我有这个 Json 返回: [
我创建了一个简单的类: public class TestObject { public TestObject(int id, string name, List list) {
我有一个像这样的 Json 对象: {"company": "My Company", "companyStart" : "2015/01/01", "employee" : { "name"
这是 json: { "odata.metadata": ".....", "value": [ { "AbsEntry": 10,
我有一个对象,其中包含一个具有 JsonConverter 属性的属性。对于数据读写,转换器不工作。声明的属性是 [JsonConverter(typeof(EpochDateTimeConverte
编辑:制作了一个更简单、更透明的示例案例 我正在尝试反序列化一组组件(属于一个实体)。其中一个组件是 Sprite 组件,它包含纹理和动画信息。我为此实现了一个 CustomConverter,因为原
我是一名优秀的程序员,十分优秀!