无法将JSON值转换为System.Collections.Generic.List`1[EnglishStudy.Entity.Word],路径:$|LineNumber:0| BytePositionInLine:1

sbtkgmzw  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(111)

我主要使用.NET 6开发,没有额外的JSON依赖项。当我在控制器中接收到一个类型为collection的参数,并使用postman工具发起Web请求时,程序返回以下结果,并显示错误消息“The JSON value could not be converted to System.Collections.Generic.List”,并且还有一个缺少字段的错误消息,postman body json数据不是问题。所以我需要知道为什么程序返回以下结果以及如何结束这个问题。
program.cs

using EnglishStudy.Service;
using EnglishStudy.Service.ServiceImpl;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddScoped<IWordService, WordServiceImpl>();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

app.Run();

字符串
Controller.cs

using EnglishStudy.Entity;
using EnglishStudy.Service;
using Microsoft.AspNetCore.Mvc;

namespace EnglishStudy.Controllers {
    [ApiController]
    [Route("word")]
    public class WordController : ControllerBase {
       
        private  Result result = new Result();

        private IWordService wordService;

        public WordController(IWordService wordService) {
            this.wordService = wordService;
        }

        [HttpPost("addlist/{type}")]
        public Result AddWord([FromBody] List<Word> wordList,int type = 1) {
            var count = wordService.AddWord(wordList,type);
            return result.Ok(count);
        }
}
}


Word.cs

using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace EnglishStudy.Entity {

    public class Word {
        public string Words { get; set; }
        public string Phonetic { get; set; }
        public string Paraphrase { get; set; }

            
    }
}


下面的HttpRequest路由

https://localhost:7031/word/addlist/1


下面是我的HttpRequest JSON数据

{
    "wordList": [
        {
            "words": "a",
            "phonetic": "a",
            "paraphrase": " art.一(个) 每一(个)"
        }
    ]
}


当我发出网络请求时,程序返回以下结果

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-bada468e083e59d9030f0fb71c9f6dfa-722ec90670eed379-00",
    "errors": {
        "$": [
            "The JSON value could not be converted to System.Collections.Generic.List`1[EnglishStudy.Entity.Word]. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
        ],
        "wordList": [
            "The wordList field is required."
        ]
    }
}


我想知道如何解决这个问题

wecizke3

wecizke31#

你的列表被JSON字符串中的单词 Package 起来。所以你必须创建一个根类

public class Root
{
List<Word> wordList {get; set;}
}

字符串
并更改活动标题

public Result AddWord([FromBody] Root root,int type = 1)
 {
   var wordsList=root.wordList;

vfwfrxfs

vfwfrxfs2#

我同意上面和评论中的帖子。我想在这里补充一些基本的解释。通常来说,输入参数决定了我们需要传递什么。因此,你在代码中用List<Word>定义了输入参数,你需要传递一个列表。让我们看看下面的例子,第一个是一个列表,因为它被[]包围,第二个是一个对象,因为它被{}包围。当然,我们可以像Serge说的那样添加一个根类,我们也可以像Ian说的那样删除wordList

[
    "property1":{},//大括号代表对象
    "property2":"",
    "property3":[]//中括号代表数组
]

{
    "property1":[]
}

字符串
if I needed a lot of different types of List parameters, I would need to create a lot of files, resulting in a lot of project files
通常来说,我们根据业务创建模型类,例如,我们有一个控制器,它被设计用于管理user,那么我们应该创建一个User类,其中包括所有需要的类型,如username, id, age, role,如果我们试图定义一个API,它被设计用于管理多个目标,例如用户沿着用户角色+用户订单+用户历史+其他一些信息,那么我们确实需要创建很多文件,我认为这也代表了面向对象编程。下面是示例和测试结果。

[Route("word")]
[ApiController]
public class WordController : ControllerBase
{
    [HttpPost("addlist/{type}")]
    public IActionResult AddWord([FromBody] Root root, int type = 1)
    {
        var count = 1;
        return Ok(count);
    }
}

public class Word
{
    public string Words { get; set; }
    public string Phonetic { get; set; }
    public string Paraphrase { get; set; }
}

public class Word2
{
    public int MyProperty { get; set; }
}

public class Root { 
    public List<Word> wordList { get; set; }
    public List<Word2> wordList2 { get; set; }
    public string prop1 { get; set; }
}


的数据
但是我们可以拒绝像JS那样创建这么多类,只需要将输入参数定义为一个JsonObject . Sample和测试结果,就像下面这样。但是我们可以明显看到,获取目标值更加复杂,而且这也给帮助理解请求体中每个属性的用法带来了很多麻烦。所以最好为模型创建类。

using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Text.Json.Nodes;

[Route("word")]
[ApiController]
public class WordController : ControllerBase
{
    [HttpPost("addlist/{type}")]
    public IActionResult AddWord([FromBody] JsonObject root, int type = 1)
    {
        var res = root["prop1"];
        var res2 = root["wordList"];
        var res3 = root["wordList"].AsArray()[0]["words"];

        return Ok();
    }
}


相关问题