将 json 转换为 C# 对象
convert json to c# object
我的 C# 模型
public class Student
{
public string id{get;set;}
[System.Text.Json.Serialization.JsonPropertyName("ref")]
public int @ref{get;set;}
}
我的ASP.Net核心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
字符串在 id
之后缺少 "
,因此无法正确解析它,因为它无效。一旦你得到正确的 JSON
字符串,那么你应该能够正确地将它解析为你的 Student
class.
您可以在此处验证您的 JSON 是否有效:https://jsonlint.com/
为什么不将 属性 @ref 更改为引用或其他内容?还有很多其他的话,你不需要使用 c# reserved
public class Student
{
public string id{get;set;}
[System.Text.Json.Serializer.JsonPropertyName("ref")]
public int reference {get;set;}
}
我的 C# 模型
public class Student
{
public string id{get;set;}
[System.Text.Json.Serialization.JsonPropertyName("ref")]
public int @ref{get;set;}
}
我的ASP.Net核心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
字符串在 id
之后缺少 "
,因此无法正确解析它,因为它无效。一旦你得到正确的 JSON
字符串,那么你应该能够正确地将它解析为你的 Student
class.
您可以在此处验证您的 JSON 是否有效:https://jsonlint.com/
为什么不将 属性 @ref 更改为引用或其他内容?还有很多其他的话,你不需要使用 c# reserved
public class Student
{
public string id{get;set;}
[System.Text.Json.Serializer.JsonPropertyName("ref")]
public int reference {get;set;}
}