Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# JsonConvert.DeserializeObject returns null with valid json file

I have the following function:

[HttpPost]
[Route("api/post")]
public void AddFavourite([FromBody]int id) {

    var data = GetData(id);
    var list = JsonConvert.DeserializeObject<List<VehicleDetail>>(@"C:\FleetStudio\favVehicle.json");
    list.Add(data);
    var convertedJson = JsonConvert.SerializeObject(list, Formatting.Indented);
 }

My list is null however and returns the following error:

Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: C. Path '', line 0, position 0.'

My data.json looks like the following (and passes the test on https://jsonlint.com/)

[
  {
    "Name": "mocksson",
    "Id": 32,
    "Alarm": null,
    "Signalinfo": null,
    "Position": null
  }
]

and my VehicleDetail class look like the following:

 public class VehicleDetailsClass
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public List<Alarms> Alarm { get; set; }
        public List<SignalInfo> Signalinfo { get; set; }
        public Position Position { get; set; }
    }

I don't see in any way how the list can be null. There is nothing exciting to this line of code, and it still manages to crash. Does anyone see where it all goes wrong?

like image 603
maac Avatar asked Jun 23 '26 11:06

maac


1 Answers

use File.ReadAllText to read your jsonData from file in disk, then pass the jsonData be parameter in JsonConvert.DeserializeObject

JsonConvert.DeserializeObject method parses json string instead of filePath.

 string jsonDATA = File.ReadAllText(@"C:\FleetStudio\favVehicle.json")
 var list = JsonConvert.DeserializeObject<List<VehicleDetail>>(jsonDATA);
like image 77
D-Shih Avatar answered Jun 25 '26 01:06

D-Shih