c# 读取 json 文件,'解析值时遇到意外字符:s。路径 '',第 0 行,位置 0。'

问题描述 投票:0回答:1

我目前正在使用 Blazor WebAssembly。 这是我尝试使用 nuGet Newtonsoft.Json 反序列化时遇到的错误。 '解析值时遇到意外字符:s。路径 '',第 0 行,位置 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
}]

我的**对象**:

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; }
    }

最后,这是**错误**发生的地方:

            try
            {
                var serializer = new JsonSerializer();

                using (var sr = new StringReader(jsonFile))
                {
                    using (var jsonTextReader = new JsonTextReader(sr))
                    {
                        jsonTextReader.SupportMultipleContent = true;
            here -->    while (jsonTextReader.Read())
                        {
                            var moto = serializer.Deserialize<MotoDTO>(jsonTextReader);
                            _motos.Add(moto);
                        }

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

有人可以帮助我吗? 谢谢

我在这里得到了代码https://stackoverflow.com

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; }
    }
}

c# json json.net blazor deserialization
1个回答
0
投票

你Dto的属性名和json数据不匹配。 并且您想反序列化为单个 Dto,但您的 json 数据是一个数组。 这是你可以反序列化的人:

 public void Deserialize()
    {
        string jsonData = @"[
    {
        ""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
    }
    ]";

        var obj = JsonConvert.DeserializeObject<List<MotoDTO>>(jsonData);

    }

调整后的DTO

using Newtonsoft.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; }
    }

现在为了从 wwwroot 文件夹中获取文件,您必须使用 httpClient

@inject HttpClient Client

@code
{

    private List<MotoDTO> motos;

    protected override async Task OnInitializedAsync()
    {
        motos = await LoadMotosFromJsonAsync();
    }

    private async Task<List<MotoDTO>> LoadMotosFromJsonAsync()
    {
        var response = await Client.GetAsync("sample-data/DB_Moto.json");

        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<List<MotoDTO>>(content);
        }
        else
        {
            return new List<MotoDTO>();
        }
    }
}

请确保 HttpClient 已在应用程序中注册

public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("#app");
            builder.RootComponents.Add<HeadOutlet>("head::after");
            builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

            await builder.Build().RunAsync();
        }
© www.soinside.com 2019 - 2024. All rights reserved.