gpt4 book ai didi

c# - System.Text.Json 自定义 JsonConverter .Read() 方法未被 .Deserialize() 使用

转载 作者:行者123 更新时间:2023-12-02 03:16:21 31 4
gpt4 key购买 nike

我在使用 System.Text.Json 和自定义日期时间格式时遇到问题。

我创建了一个自定义转换器,它正在我的 api 项目中运行。当我构建客户端时,我尝试使用相同的类,但是 .Deserialize() 方法不会在我的类的 DateTime 属性上调用 .Read() 。

有人遇到过同样的问题吗?

public class DateTimeConverter : JsonConverter<DateTime>
{
private static readonly string _format = "yyyy-MM-dd'T'HH:mm:ss.fff";

public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.ParseExact(reader.GetString(), _format, System.Globalization.CultureInfo.InvariantCulture);
}

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToUniversalTime().ToString(_format));
}

public async Task<StockUnitInfo> GetStockUnitInfoAsync(Inbound inbound, CancellationToken token = default)
{
var uri = Uri.EscapeUriString($"{_httpClient.BaseAddress}/Readers/{inbound.Position}/StockUnits/{inbound.Barcode}");

var test = await _httpClient.GetStringAsync(uri);

var response = await _httpClient.GetStreamAsync(uri);

var _serializationOptions = new JsonSerializerOptions
{
Converters = { new DateTimeConverter() }
};

return await JsonSerializer.DeserializeAsync<StockUnitInfo>(response, _serializationOptions, token);
}

public class StockUnitInfo
{
public string barcode { get; set; }
public string wms_batch_id { get; set; }
public string gtin { get; set; }

//[JsonConverter(typeof(DateTimeConverter))]
public DateTime sort_date { get; set; }
public string talleys_batch_number { get; set; }
public int expected_batch_size { get; set; }
public string destination { get; set; }
public bool fast_mover { get; set; }
public int stackable { get; set; }
public string message { get; set; }
}

根据要求的最小可重现示例:

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

class Program
{
public class DateTimeConverter : JsonConverter<DateTime>
{
//private static readonly string _format = "yyyy.MM.dd'T'HH:mm:ss.fff'Z'"; //formato api?
private static readonly string _format = "yyyy-MM-dd'T'HH:mm:ss.fff";


public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.ParseExact(reader.GetString(), _format, System.Globalization.CultureInfo.InvariantCulture);
}

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToUniversalTime().ToString(_format));
}
public class StockUnitInfo
{
public string barcode { get; set; }
public string wms_batch_id { get; set; }
public string gtin { get; set; }

//[JsonConverter(typeof(DateTimeConverter))]
public DateTime sort_date { get; set; }
public string talleys_batch_number { get; set; }
public int expected_batch_size { get; set; }
public string destination { get; set; }
public bool fast_mover { get; set; }
public int stackable { get; set; }
public string message { get; set; }
}
public static void Main(string[] args)
{
string json = "{\"barcode\":\"201930823\",\"wmsBatchId\":\"c3e4d921-8779-46f7-ac28-b1f523845329\",\"gtin\":\"01080\",\"sortDate\":\"2019-09-20T11:59:59.999\",\"talleysBatchNumber\":\"STK0233\",\"expectedBatchSize\":1,\"destination\":\"5A05\",\"fastMover\":false,\"stackable\":0,\"message\":\"Pallet directed to CS4\"}";

var _serializationOptions = new JsonSerializerOptions
{
Converters = { new DateTimeConverter() }
};
var result = JsonSerializer.Deserialize<StockUnitInfo>(json, _serializationOptions);

Console.WriteLine(result.sort_date);
Console.Read();
}
}

最佳答案

出现这种情况的原因是类属性的名称和Json属性的名称不同:

"sortDate": "2019-09-20T11:59:59.999"

还有

public DateTime sort_date { get; set; }

为了反序列化该 json,您需要使名称相同,或者通过添加属性来告诉序列化程序要执行的操作来告诉等效名称是什么:

// For NewtonSoft.Json
// [JsonProperty("sortDate")]

// For System.Text.Json
[JsonPropertyName("sortDate")]
public DateTime sort_date { get; set; }

添加后,您的示例代码将正确运行:

enter image description here

关于c# - System.Text.Json 自定义 JsonConverter<DateTime> .Read() 方法未被 .Deserialize() 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59733697/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com