Search code examples
c#jsonjson.netblazordeserialization

c# reading json file, 'Unexpected character encountered while parsing value: s. Path '', line 0, position 0.'


I'm currently using Blazor WebAssembly. This is the error i'm getting when I try to Deserialize with the nuGet Newtonsoft.Json. 'Unexpected character encountered while parsing value: s. Path '', line 0, position 0.'

This is my JSON file :

[{
    "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
}]

And my **object **:

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

And finaly, this is where the **error **occurs :

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

Could somebody help me ? Thanks

I got the code here 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; }
    }
}


Solution

  • You Dto's property names do not match the json data. And you want to deserialize to a single Dto but your json data is an array. Here's who you can deszerialize it:

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

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

    Now in order to fetch the file from the wwwroot folder you have to use the 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>();
            }
        }
    }
    

    please make sure the HttpClient is registerd in the app

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