“JsonException:JSON 值无法转换为 NodaTime.Instant”ASP.NET Core 3.1 Razor Page Web 应用程序的 NodaTime 问题

问题描述 投票:0回答:1
asp.net-core razor-pages asp.net-core-3.1 nodatime json-serialization
1个回答
1
投票
在当前版本的

JsonSerializerOptions

中,无法将
System.Text.Json
设置为全局。这可以通过在需要的地方构建选项来解决:

var jsonString = "{\"data\":[{\"id\":\"f606942c-4740-46a7-be6f-66ceb38c530b\",\"created_at\":\"2020-08-09T22:10:26.274672Z\",\"updated_at\":\"2020-08-13T02:22:02.640871Z\"}],\"page\":1,\"size\":20,\"count\":1,\"total\":1,\"success\":true,\"message\":null }";
    
JsonSerializerOptions options = new JsonSerializerOptions();
options.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
options.Converters.Add(new JsonStringEnumConverterWithAttributeSupport(null, true, true, true, true));

var response = JsonSerializer.Deserialize<Response>(jsonString, options);

    
public enum SampleType
{
    TYPE_0,
    TYPE_1
}

public class Sample
{
    [JsonProperty("id")]
    public string Id { get; set; } = System.Guid.NewGuid().ToString();
    [JsonProperty("created_at")]
    public Instant CreatedAt { get; set; }
    [JsonProperty("updated_at")]
    public Instant UpdateAt { get; set; }

    [JsonProperty("type")]
    public SampleType Type { get; set; }
}

public class Response
{
    [JsonProperty("data")]
    public IEnumerable<Sample> Data { get; set; }
    
    [JsonProperty("page")]
    public int Page { get; set; }
    
    [JsonProperty("size")]
    public int Size { get; set; }
    
    [JsonProperty("count")]
    public int Count { get; set; }
    
    [JsonProperty("total")]
    public int Total { get; set; }
    
    [JsonProperty("success")]
    public bool Success { get; set; }

    [JsonProperty("message")]
    public string Message { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.