c#阅读json文件,'解析值时遇到意外字符:s.路径“”,行0,位置0,”

67up9zun  于 2023-05-02  发布在  C#
关注(0)|答案(2)|浏览(233)

我目前使用的是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; }
    }
}
wixjitnu

wixjitnu1#

您的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();
        }
u3r8eeie

u3r8eeie2#

你没有任何多行,它只是一个json数组,所以既然你使用的是 www.example.com

var json = File.ReadAllText(@"C:\... .json");

List<MotoDTO> motoDtos = JsonConvert.DeserializeObject<List<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; }
}

如果出于某种原因,你想要一些异步的东西,最好使用System。Text.Json

相关问题