skip to Main Content

I am having some problems with the deserilization of my json. I have to create a rest api that search for specific results in my converted json file. First, it has to check if type is 001, then it has to list all results that have their roadname starting with a user input string.

Example of the Json file

{"type":"001","kommuneCode":"0621","roadCode":"8713","timestamp":"199109231200","roadToNextKommuneCode":"0000","roadToNextRoadCode":"0000","roadToPreviousKommuneCode":"0000","roadToPreviousRoadCode":"0000","startDate":"190001010000","roadName":"Topasvej            ","ExpandedRoadName":"Topasvej                                "}
{"type":"003","kommuneCode":"0621","roadCode":"8713","houseNumberFrom":"002 ","HouseNumberTo":"030 ","evenUneven":"L","timestamp":"201809292139","townName":"Seest                             "}
{"type":"003","kommuneCode":"0621","roadCode":"8713","houseNumberFrom":"001 ","HouseNumberTo":"027 ","evenUneven":"U","timestamp":"201809292139","townName":"Seest                             "}
{"type":"004","kommuneCode":"0621","roadCode":"8713","houseNumberFrom":"002 ","HouseNumberTo":"030 ","evenUneven":"L","timestamp":"201809292110","postNumber":"6000","postalDistrict":"Kolding             "}
{"type":"004","kommuneCode":"0621","roadCode":"8713","houseNumberFrom":"001 ","HouseNumberTo":"027 ","evenUneven":"U","timestamp":"201809292110","postNumber":"6000","postalDistrict":"Kolding             "}
{"type":"009","kommuneCode":"0621","roadCode":"8713","houseNumberFrom":"002 ","houseNumberTo":"030 ","evenUneven":"L","timestamp":"201809292202","churchCode":"23","districtText":"Seest                         "}
{"type":"009","kommuneCode":"0621","roadCode":"8713","houseNumberFrom":"001 ","houseNumberTo":"027 ","evenUneven":"U","timestamp":"201809292202","churchCode":"23","districtText":"Seest                         "}
{"type":"013","kommuneCode":"0621","roadCode":"8713","houseNumberFrom":"002 ","houseNumberTo":"030 ","evenUneven":"L","timestamp":"201809292203","authorityCode":"8940","districtText":"Seest,Kolding       "}
{"type":"013","kommuneCode":"0621","roadCode":"8713","houseNumberFrom":"001 ","houseNumberTo":"027 ","evenUneven":"U","timestamp":"201809292203","authorityCode":"8940","districtText":"Seest,Kolding       "}
{"type":"014","kommuneCode":"0621","roadCode":"8713","houseNumberFrom":"002 ","houseNumberTo":"030 ","evenUneven":"L","timestamp":"201809292202","electionCode":"10","districtText":"Seest                         "}
{"type":"014","kommuneCode":"0621","roadCode":"8713","houseNumberFrom":"001 ","houseNumberTo":"027 ","evenUneven":"U","timestamp":"201809292202","electionCode":"10","districtText":"Seest                         "}
{"type":"001","kommuneCode":"0621","roadCode":"8724","timestamp":"199109231200","roadToNextKommuneCode":"0000","roadToNextRoadCode":"0000","roadToPreviousKommuneCode":"0000","roadToPreviousRoadCode":"0000","startDate":"190001010000","roadName":"Toppen              ","ExpandedRoadName":"Toppen                                  "}

My model class SearchAllRoadNames that I use in my rest api

namespace John_Høeg_opgave_4._1.Models
{
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Reflection.Metadata;

    public class SearchAllRoadNames
    {
        public string type { get; set; }
        public string kommuneCode { get; set; }
        public string roadCode { get; set; }
        public string timestamp { get; set; }
        public string roadToNextKommuneCode { get; set; }
        public string roadToNextRoadCode { get; set; }
        public string roadToPreviousKommuneCode { get; set; }
        public string roadToPreviousRoadCode { get; set; }
        public string startDate { get; set; }
        public string roadName { get; set; }
        public string ExpandedRoadName { get; set; }

    }
}

And my rest api RoadNamesController

using John_Høeg_opgave_4._1.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Text.Json.Nodes;

namespace John_Høeg_opgave_4._1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RoadNamesController : ControllerBase
    {
        [HttpGet]
        public SearchAllRoadNames Get(string value)
        {
            SearchAllRoadNames roadNames = new SearchAllRoadNames();
            var jsonFilePath = "C:\Users\Saphy\OneDrive\Softwareudvikling\SystemIntegration\John Høeg opgave 4.1\path.json";
            var jsonString = System.IO.File.ReadAllText(jsonFilePath);
            List<SearchAllRoadNames> jsonList = JsonConvert.DeserializeObject<List<SearchAllRoadNames>>(jsonString);
            // Filter the list based on the specified type and road name filter
            string searchType = "001";
            string roadNameFilter = value;
            List<SearchAllRoadNames> filteredList = jsonList.Where(x => x.type == searchType && x.roadName.StartsWith(roadNameFilter)).ToList();
            // Display the filtered results
            foreach (SearchAllRoadNames obj in filteredList)
            {
                roadNames.roadName = obj.roadName;
                
            }
            return roadNames;

            
        }
    }
}

The error I get is:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[John_Høeg_opgave_4._1.Models.SearchAllRoadNames]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'type', line 1, position 8.'

2

Answers


  1. Chosen as BEST ANSWER

    Managed to find a solution to my problem. Thank you gbjbaanb for find the initial problem.

    Fixed the JSON. So that its properly formatted, that way the Deserialiser can properly read it.

    Example code

    [
      {
        "type": "001",
        "kommuneCode": "0010",
        "roadCode": "0070",
        "timestamp": "199109231200",
        "roadToNextKommuneCode": "0000",
        "roadToNextRoadCode": "0000",
        "roadToPreviousKommuneCode": "0000",
        "roadToPreviousRoadCode": "0000",
        "startDate": "190001010000",
        "roadName": "Norge               ",
        "ExpandedRoadName": "Norge                                   "
      },
      {
        "type": "001",
        "kommuneCode": "0010",
        "roadCode": "0071",
        "timestamp": "199109231200",
        "roadToNextKommuneCode": "0000",
        "roadToNextRoadCode": "0000",
        "roadToPreviousKommuneCode": "0000",
        "roadToPreviousRoadCode": "0000",
        "startDate": "190001010000",
        "roadName": "Sverige             ",
        "ExpandedRoadName": "Sverige                                 "
      },
      {
        "type": "001",
        "kommuneCode": "0010",
        "roadCode": "0072",
        "timestamp": "199109231200",
        "roadToNextKommuneCode": "0000",
        "roadToNextRoadCode": "0000",
        "roadToPreviousKommuneCode": "0000",
        "roadToPreviousRoadCode": "0000",
        "startDate": "190001010000",
        "roadName": "Finland             ",
        "ExpandedRoadName": "Finland                                 "
      },
    

    I also noticed a problem in my model view. It was missing its constructor... newbie error :P

    namespace John_Høeg_opgave_4._1.Models
    {
        using Newtonsoft.Json;
        using Newtonsoft.Json.Linq;
        using System;
        using System.Collections.Generic;
        using System.IO;
        using System.Reflection.Metadata;
    
        public class SearchAllRoadNames
        {
            public SearchAllRoadNames()
            {
                
            }
    
            public string type { get; set; }
            public string kommuneCode { get; set; }
            public string roadCode { get; set; }
            public string timestamp { get; set; }
            public string roadToNextKommuneCode { get; set; }
            public string roadToNextRoadCode { get; set; }
            public string roadToPreviousKommuneCode { get; set; }
            public string roadToPreviousRoadCode { get; set; }
            public string startDate { get; set; }
            public string roadName { get; set; }
            public string ExpandedRoadName { get; set; }
    
        }
    }
    
    

    And lastly I entirely changed the code for the rest API so that it works properly. Accidently made it so it only showed 1 result. And instead of roadname it showed the entire class.

    using John_Høeg_opgave_4._1.Models;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Newtonsoft.Json;
    using System.Collections.Generic;
    using System.Text.Json.Nodes;
    
    namespace John_Høeg_opgave_4._1.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class RoadNamesController : ControllerBase
        {
            [HttpGet]
            public List<string> Get(string value)
            {
                var jsonFilePath = "C:\Users\Saphy\OneDrive\Softwareudvikling\SystemIntegration\John Høeg opgave 4.1\class001File.json";
                var jsonString = System.IO.File.ReadAllText(jsonFilePath);
                var jsonList = JsonConvert.DeserializeObject<List<SearchAllRoadNames>>(jsonString);
                // Filter the list based on the specified type and road name filter
                string roadNameFilter = value;
                var filteredList = jsonList.Where(x => x.roadName.StartsWith(roadNameFilter)).Select(x => x.roadName).ToList();
                return filteredList;
            }
        }
    }
    
    

    Thanks all.


  2. Your JSON is not an array, but you’re trying to deserialise it as one.

    Put square brackets around the entire thing, commas at the end of eahc line and you should be good.

    Also, Microsoft updated their json library to replace Newtonsoft. Use System.Text.Json to get the calls that are pretty much the same as Newtonsoft’s.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search