相关疑难解决方法(0)

使用System.Text.Json在ASP.NET Core 3.0中格式化DateTime

我正在将Web API从.NET Core 2.2迁移到3.0,并希望使用新的API System.Text.Json。使用时,Newtonsoft我可以DateTime使用以下代码进行格式化。我该怎么做?

.AddJsonOptions(options =>
    {
        options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
        options.SerializerSettings.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZ";
    });
Run Code Online (Sandbox Code Playgroud)

c# datetime json asp.net-core system.text.json

7
推荐指数
3
解决办法
1967
查看次数

将多个 JSON 属性名称映射到 System.Text.Json 中的同一属性

我正在编写一个使用 API 的客户端(我无法控制该 API)。不幸的是,API 的不同端点返回命名不一致的 JSON 字段。例如,一个端点正在返回errorCode,但另一个端点可能会返回ErrorCode

System.Text.Json我在 .NET Core 应用程序中使用它来进行序列化。我想做如下的事情:

public class MyErrorsResponse
{
    [JsonPropertyName("errorCode")]
    [JsonPropertyName("ErrorCode")]
    public string Code { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这在编译时是不允许的,我收到错误:CS0579 Duplicate 'JsonPropertyName' attribute

无论如何,这个问题有解决办法吗?我尝试了第二个私有设置器的想法,例如:将多个 JsonProperty Name 分配给单个属性。然而,看起来System.Text.Json只序列化公共字段而忽略私有字段。

c# json .net-core system.text.json

7
推荐指数
0
解决办法
3984
查看次数

System.Text.Json 从 API 调用反序列化嵌套对象 - 数据包装在父 JSON 属性中

我有一个 API JSON 响应,它将数据内容包装在一个data属性中,如下所示:

{ 
   "data":{ 
      "email":"admin@example.com",
      "mobile":"+1555555123",
      "id":4,
      "first_name":"Merchant",
      "last_name":"Vendor",
      "role":"Merchant",
   }
}
Run Code Online (Sandbox Code Playgroud)

所以使得用户对象的请求时就像一个图书馆RequestSharp,将response.Content有包裹在用户的内容dataJSON属性作为它来自API。代码:

var request = RequestHelper.CreateTokenRequest(email, password); // Create the request from a helper
var client = new RestClient(BaseUrl); // create new RestSharp Client
IRestResponse response = client.Execute(request); // execute the request
var content = response.Content; // raw content as string
Run Code Online (Sandbox Code Playgroud)

这很好,但是当我将 json 反序列化为对象时System.Text.Json,如下所示,将创建User对象但不会分配任何属性,尽管这是预期的,因为序列化程序正在寻找带有first_name和的属性last_name。 .. 不是['data']['first_name']

User account = JsonSerializer.Deserialize<User>(response.Content, …
Run Code Online (Sandbox Code Playgroud)

.net c# json .net-core system.text.json

4
推荐指数
1
解决办法
6695
查看次数

System.Text.Json转换器获取整个字符串对象

所以我遇到的情况是我的 NewtonJson 自定义转换器无法与 body api 调用一起使用。(默认使用 System.Text.Json 进行转换)。

所以目前我有一个临时解决方案来编写一些包装器,这些包装器最终将调用 Newtonjson,直到编写并测试 text.json 转换器。

我想做的是将整个对象作为字符串读取并将其传递给牛顿转换器

我的 StartUp.cs

 services.AddControllers(options =>
        options.Filters.Add<ApiExceptionFilterAttribute>())
            .AddFluentValidation(x => x.AutomaticValidationEnabled = false)//ValidationBehaviour handle fluent validations.
            .AddJsonOptions(x =>
            {
                x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                x.JsonSerializerOptions.Converters.Add(new SystemModelConverter());
                x.JsonSerializerOptions.IgnoreNullValues = true;
            });
Run Code Online (Sandbox Code Playgroud)

我的转换器类

 public class SystemModelConverter : JsonConverter<ISystemModel>
{
    public override bool CanConvert(Type typeToConvert)
    {
        return (typeToConvert.GetInterface(typeof(ISystemModel).Name) != null);
    }

    public override ISystemModel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var value = new StringBuilder();
        while(reader.Read())
        {
            var str = reader.GetString();
            value.Append(str);
        }
        //passing …
Run Code Online (Sandbox Code Playgroud)

.net c# json system.text.json

2
推荐指数
1
解决办法
2025
查看次数

标签 统计

c# ×4

json ×4

system.text.json ×4

.net ×2

.net-core ×2

asp.net-core ×1

datetime ×1