相关疑难解决方法(0)

JsonSerializer.Deserialize 失败

考虑代码...

using System;
using System.Text.Json;

public class Program
{
    public static void Main()
    {
        int id = 9;
        string str = "{\"id\": " + id + "}";
        var u = JsonSerializer.Deserialize<User>(str);
        Console.WriteLine($"User ID: {u.Id}, Correct: {id == u.Id}");  // always 0/init/default value
    }
}


public class User {
    public int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

为什么数据没有正确反序列化到User对象中?我还通过DotNetFiddle验证了该行为,以防它是我系统的本地问题。不会抛出任何异常。

我的实际执行是从读[ApiController][HttpPost]后我的行动return Created("user", newUser)。它在我的 MVC/Razor 项目中通过_httpClient.PostAsync. 我在Created返回到PostAsync调用时验证了这些值是正确的,但无论如何,从响应正文解析的值仅包含默认值(实际 ID …

c# asp.net-core-mvc .net-core-3.1 system.text.json

10
推荐指数
1
解决办法
1万
查看次数

当属性和构造函数参数类型不同时,System.Text.Json(但不是 Newtonsoft.Json)中的 JsonConstructorAttribute 会导致异常

给定 Base64 字符串,以下示例类将使用Newtonsoft.Json正确反序列化,但不能使用System.Text.Json

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

public class AvatarImage{

  public Byte[] Data { get; set; } = null;

  public AvatarImage() {
  }

  [JsonConstructor]
  public AvatarImage(String Data) {
  //Remove Base64 header info, leaving only the data block and convert it to a Byte array
    this.Data = Convert.FromBase64String(Data.Remove(0, Data.IndexOf(',') + 1));
  }

}
Run Code Online (Sandbox Code Playgroud)

对于 System.Text.Json,会引发以下异常:

must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the …
Run Code Online (Sandbox Code Playgroud)

json constructor .net-5 system.text.json

5
推荐指数
1
解决办法
3946
查看次数

ASP.NET Core 绑定区分大小写

我创建了 CRUD 控制器。创建模型时,我需要使用架构:

{ "id": int, "name": string }
Run Code Online (Sandbox Code Playgroud)

但控制器也绑定了模式

{ "Id": int, "Name": string }
Run Code Online (Sandbox Code Playgroud)

如何强制控制器仅绑定小写版本{ "id": int, "name": string }

c# binding asp.net-web-api asp.net-core

3
推荐指数
1
解决办法
8905
查看次数