Home > database >  Message = "Unexpected character encountered while parsing value: [. Path '', line 1,
Message = "Unexpected character encountered while parsing value: [. Path '', line 1,

Time:03-20

I want to show list of departments in my ASP.NET Core MVC view.

Notice that I have 3-tier layers (Data Access API (to get data from database) MVC (UI)).

Here is my Json Data that I got from database using a call to the API:

[
  {
    "id": 3,
    "name": "Sales"
  },
  {
    "id": 4,
    "name": "PMO"
  },
  {
    "id": 5,
    "name": "Research And Development"
  },
  {
    "id": 6,
    "name": "Product Management"
  },
  {
    "id": 7,
    "name": "HR"
  },
  {
    "id": 8,
    "name": "Ava"
  },
  {
    "id": 9,
    "name": "IT"
  }
]

Here is my C# code using HttpClient to get data from the API:

public async Task<T> GetRequest<T>(string uri)
{
        try
        {
            var client = _httpClientFactory.CreateClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            using (HttpResponseMessage response = await client.GetAsync(uri))
            {
                if (response.StatusCode.ToString() == "OK")
                {
                    _logger.LogInformation("Get Request Successed");
                    //response.EnsureSuccessStatusCode();
                   responseBody = await response.Content.ReadAsStringAsync();
                }

                return JsonConvert.DeserializeObject<T>(responseBody);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError("Failed");
            return JsonConvert.DeserializeObject<T>(responseBody);
        }
}

When I am trying to parse the data from json it returns an Error.

Unexpected character encountered while parsing value: [. Path '', line 1, position 1.

CodePudding user response:

You can parse your string to a strongly typed Model and then de-serialize to it OR you can use dynamic and access the properties as shown below:

You can find a working example here

using System;
using Newtonsoft.Json;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        var myJsonString=@"[{'id':3,'name':'Sales'},{'id':4,'name':'PMO'},{'id':5,'name':'Research And Development'},{'id':6,'name':'Product Management'},{'id':7,'name':'HR'},{'id':8,'name':'Ava'},{'id':9,'name':'IT'}]";
        var result =JsonConvert.DeserializeObject<List<Root>>(myJsonString);
        Console.WriteLine("Example using Model: \n");
        foreach(var item in result)
        {
            Console.WriteLine(item.id);
            Console.WriteLine(item.name);           
        }
        
        Console.WriteLine("\n");
        Console.WriteLine("Example using Dynamic: \n");
        
        //Example using dynamic
        var resultDynamic=JsonConvert.DeserializeObject<dynamic>(myJsonString);
        foreach(var item in resultDynamic)
        {
            Console.WriteLine(item["id"]);
            Console.WriteLine(item["name"]);        
        }
    }
}

public class Root
{
    public int id { get; set; }
    public string name { get; set; }
}

Output:

Example using Model: 

3
Sales
4
PMO
5
Research And Development
6
Product Management
7
HR
8
Ava
9
IT


Example using Dynamic: 

3
Sales
4
PMO
5
Research And Development
6
Product Management
7
HR
8
Ava
9
IT
  • Related