首页 > 解决方案 > json数组解析错误,应用程序完成而没有读取整个请求体

问题描述

我在这个问题上停留了 4 个多小时。我的 json 看起来很好,至少对 jsonLint 来说,这是一个例子:

[{
    "cnpj": "1",
    "notasPorConsulta": "1",
    "partirDe": "1"
}, {
    "cnpj": "2",
    "notasPorConsulta": "2",
    "partirDe": "2"
}]

或者

{
    "NovoRastreio": [{
        "cnpj": "1",
        "notasPorConsulta": "1",
        "partirDe": "1"
    }, {
        "cnpj": "2",
        "notasPorConsulta": "2",
        "partirDe": "2"
    }]
}

这是我使用 javascript 发布的方式。

(async () => {
        console.log(NovoRastreio);
        const fetchResp = await fetch('api/values/NovoRastreio', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: NovoRastreio
        })
        .then();
            .then(res => console.log(res.json()));
    })();

我也试过没有异步/等待。没有成功。

首先,我创建了一个基本模型,然后使用 QuickType 生成了另一个模型,就在这里。

public partial class NovoRastreio
    {
        [JsonProperty("NovoRastreio")]
        public List<NovoRastreioElement> Rastreios { get; set; }
    }

    public partial class NovoRastreioElement
    {
        [JsonProperty("cnpj")]
        public string Cnpj { get; set; }

        [JsonProperty("notasPorConsulta")]
        [JsonConverter(typeof(ParseStringConverter))]
        public long NotasPorConsulta { get; set; }

        [JsonProperty("partirDe")]
        [JsonConverter(typeof(ParseStringConverter))]
        public long PartirDe { get; set; }
    }

而我的控制器,我删除了所有代码,只留下了一个简单的控制台编写器,看看它是否可以工作。

[HttpGet("NovoRastreio")]
        public void NovoRastreioPorCnpj([FromBody]NovoRastreio rastreios )
        {
            System.Console.WriteLine(rastreios);
        }

不,我每次都从标题中得到错误,即使我尝试使用邮递员,而且,我在同一个 API 中有多个其他帖子,它工作正常,不同的是另一个只发布一个 JSON 对象,而不是多个对象的列表/数组。

标签: c#jsonasp.net-core

解决方案


好的,您[JsonProperty("NovoRastreio")]在您的class NovoRastreio但在您的 json 中声明没有具有此类名称的字段。尝试发送这样的东西:

{
  "NovoRastreio":
    [{
        "cnpj": "1",
        "notasPorConsulta": "1",
        "partirDe": "1"
    }, {
        "cnpj": "2",
        "notasPorConsulta": "2",
        "partirDe": "2"
    }]
}

推荐阅读