【问题标题】:convert json to c# object [closed]将json转换为c#对象[关闭]
【发布时间】:2022-01-25 12:47:25
【问题描述】:

我的 c# 模型

public class Student
{
  public string id{get;set;}
  [System.Text.Json.Serialization.JsonPropertyName("ref")]
  public int @ref{get;set;}
}

我的 ASP.Net Core API 方法

[HttpPost]
public async Task<IActionResult> Get([FromBody] Student stu)
{
   var reference = stu.@ref;
   //Here stu.@ref is always 0.
   //JSON to C# model conversion doesnt work
}

以下是请求正文

{
  "id":"74A",
  "ref":41
}

C# 不允许声明变量名“ref”,所以我声明为“@ref”并用 JsonPropertyName(“ref”) 修饰它。但是 json 到 c# 模型反序列化不会将 ref 映射到 @ref。

任何解决方案或变通方法。

【问题讨论】:

  • 似乎是无效的 json。 ???你试过json2csharp.com 吗?
  • my internet上工作。
  • "这里 stu.@ref 始终为 0。"但是 stu.id 呢?
  • stu.id 是“74A”。 Json 到 c# 模型适用于 id 属性
  • 请发布您的实际代码。 System.Text.Json.Serializer.JsonPropertyName 不是正确的命名空间,而不是 Serializer 应该是 Serialization,这让我认为可能还有其他问题。要知道该属性的 actual 属性名称将只是 ref@ 前缀只是为了让编译器不将其视为保留关键字,@ 不会实际上是属性名称的一部分。

标签: c# json .net-core asp.net-core-webapi system.text.json


【解决方案1】:

您的JSON 字符串在id 之后缺少",因此它无法正确解析它,因为它是无效的。一旦你得到正确的JSON 字符串,那么你应该能够正确地将它解析为你的Student 类。

您可以在此处验证您的 JSON 是否有效:https://jsonlint.com/

【讨论】:

    【解决方案2】:

    为什么不将属性 @ref 更改为引用或其他内容?还有很多话,不用c#reserved

    public class Student
    {
      public string id{get;set;}
      [System.Text.Json.Serializer.JsonPropertyName("ref")]
      public int reference {get;set;}
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多