You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor WebAssembly中Newtonsoft.Json反序列化JSON文件报错求助

Blazor WebAssembly中Newtonsoft.Json反序列化报错解决

报错信息

Unexpected character encountered while parsing value: s. Path '', line 0, position 0.

JSON文件内容

[
    {
        "Id": 1,
        "Brand": "Aprilia",
        "Modele": "RS 660",
        "CC": 660,
        "Nb Cylindre": 2,
        "Config cylindre": "ligne",
        "Couple": "66 Nm 8500",
        "Puissance (kW)": "XXX",
        "Puissance (cv)": "100 cv 10500",
        "Poids sec (kg)": 169,
        "Date sortie": 2023
    },
    {
        "Id": 2,
        "Brand": "Aprilia",
        "Modele": "Tuono 660",
        "CC": 660,
        "Nb Cylindre": 2,
        "Config cylindre": "ligne",
        "Couple": "66 Nm 8500",
        "Puissance (kW)": "XXX",
        "Puissance (cv)": "95 cv 10500",
        "Poids sec (kg)": 183,
        "Date sortie": 2023
    }
]

实体类MotoDTO定义

public class MotoDTO
{
    public int Id { get; set; }
    public string Brand { get; set; }
    public string Modele { get; set; }
    public int CC { get; set; }
    public int NbCylindre { get; set; }
    public string ConfigCylindre { get; set; }
    public string Couple { get; set; }
    public string PuissanceKW { get; set; }
    public string PuissanceCv { get; set; }
    public int PoidsSecKg { get; set; }
    public int DateSortie { get; set; }
}

报错代码(while循环处触发错误)

try
{
    var serializer = new JsonSerializer();

    using (var sr = new StringReader(jsonFile))
    {
        using (var jsonTextReader = new JsonTextReader(sr))
        {
            jsonTextReader.SupportMultipleContent = true;
            // 报错位置
            while (jsonTextReader.Read())
            {
                var moto = serializer.Deserialize<MotoDTO>(jsonTextReader);
                _motos.Add(moto);
            }

        }
    }
}
catch (Exception ex)
{
    string msg = ex.Message;
}

参考代码

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = @"
{'ItemName':'8','Id':1}
{'ItemName':'9','Id':2}
";

            var items = new List<Item>();

            var serializer = new JsonSerializer();

            using (var sr = new StringReader(json))
            {
                using (var jsonTextReader = new JsonTextReader(sr))
                {
                    jsonTextReader.SupportMultipleContent = true;
                    while (jsonTextReader.Read())
                    {
                        var data = serializer.Deserialize<Item>(jsonTextReader);
                        items.Add(data);
                    }

                }
            }

            foreach (Item item in items)
            {
                Console.WriteLine($"{item.Id}: {item.ItemName}");
            }
        }
    }

    public class Item
    {
        public string ItemName { get; set; }
        public int Id { get; set; }
    }
}

问题原因与解决办法

核心问题

  1. JSON结构不匹配:参考代码处理的是多行独立JSON对象(每行一个{...}),但你的JSON是单个JSON数组[...],启用SupportMultipleContent = true后解析数组会读取到非预期字符。
  2. 属性键名不映射:JSON中的键如"Nb Cylindre"、"Puissance (kW)"等,和实体类的NbCylindre、PuissanceKW无对应关系,直接反序列化会导致属性赋值失败。

解决步骤

  1. 修改反序列化逻辑适配数组结构
    无需启用SupportMultipleContent,直接将JSON数组反序列化为List<MotoDTO>:

    try
    {
        var motos = JsonConvert.DeserializeObject<List<MotoDTO>>(jsonFile);
        _motos.AddRange(motos);
    }
    catch (Exception ex)
    {
        string msg = ex.Message;
    }
    
  2. 为实体类添加JsonProperty特性映射键名
    修改MotoDTO类,标记每个属性对应的JSON键:

    public class MotoDTO
    {
        public int Id { get; set; }
        public string Brand { get; set; }
        public string Modele { get; set; }
        public int CC { get; set; }
        
        [JsonProperty("Nb Cylindre")]
        public int NbCylindre { get; set; }
        
        [JsonProperty("Config cylindre")]
        public string ConfigCylindre { get; set; }
        
        public string Couple { get; set; }
        
        [JsonProperty("Puissance (kW)")]
        public string PuissanceKW { get; set; }
        
        [JsonProperty("Puissance (cv)")]
        public string PuissanceCv { get; set; }
        
        [JsonProperty("Poids sec (kg)")]
        public int PoidsSecKg { get; set; }
        
        [JsonProperty("Date sortie")]
        public int DateSortie { get; set; }
    }
    
  3. 验证JSON字符串有效性
    确认jsonFile变量是正确的JSON文本内容,而非文件路径或其他无效内容。在Blazor WebAssembly中,若从wwwroot读取文件,需通过HttpClient获取资源内容。

内容的提问来源于stack exchange,提问作者David

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 17:15:07