【问题标题】:InvalidOperationException: Cannot get the value of a token type 'String' as a numberInvalidOperationException:无法将令牌类型 \'String\' 的值作为数字获取
【发布时间】:2022-11-29 21:44:15
【问题描述】:

试图从 json 文件中获取数据到产品列表中

试图从 json 文件中获取数据到产品列表中,但出现此错误 InvalidOperationException:无法获取令牌类型 String 的值作为数字。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text.Json.Serialization;
using System.Text.Json;
using Microsoft.AspNetCore.Hosting;
using DevTest.Website.Models;

<!-- begin snippet: js hide: false console: true babel: false -->
namespace DevTest.Website.Services
{
    public class JsonFileProductService
    {
        public JsonFileProductService(IWebHostEnvironment webHostEnvironment)
        {
            WebHostEnvironment = webHostEnvironment;
        }

        public IWebHostEnvironment WebHostEnvironment { get; }

        private string JsonFileName => Path.Combine(WebHostEnvironment.WebRootPath, "data", "products.json");

        public IEnumerable<Product> GetProducts()
        {
            using (var jsonFileReader = File.OpenText(JsonFileName))
            {
                return JsonSerializer.Deserialize<Product[]>(jsonFileReader.ReadToEnd(),
                new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });
            }

        }
    }
}

【问题讨论】:

  • 你能显示你的代码吗?
  • public IEnumerable<Product> GetProducts() { 使用 (var jsonFileReader = File.OpenText(JsonFileName)) { return JsonSerializer.Deserialize<Product[]>(jsonFileReader.ReadToEnd(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } }

标签: c# asp.net json .net web


【解决方案1】:

没有任何源代码很难说,但可能导致这种情况的潜在问题:

  • 读取与写入时的不同模型/dto
  • 数据可以序列化为某种类型 T,您尝试将其转换为字符串,或者数据为字符串但您尝试将其反序列化为 T。

我会将您的 json 数据类型与您的 C# 模型进行比较。 如果您使用 JsonSerializer.Deserialize,您可以尝试使用 Newtonsoft.Json 中的 JsonConvert.DeserializeObject,但我会首先尝试找出您的模型和 json 文件之间的区别。

【讨论】:

  • 无法上传图片,已添加代码,感谢高亮显示
  • 您可以为要反序列化的产品类和示例 json 文件添加代码吗?在评论或 pastbin.com
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 2011-12-07
相关资源
最近更新 更多