3

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?

2
  • 1
    JsonConvert doesn't read the file, it is trying to deserialize your path, which isn't json. Commented Jul 20, 2018 at 7:30
  • Using [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] on fields might help... Commented Apr 11, 2020 at 15:09

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

It did the trick. I also added the following line, File.WriteAllText(@"C:\FleetStudio\favVehicle.json", convertedJson); , which now also write the result to my .json file. Appreciate the help a lot D-Shih.
Thanks :) glad to help @maac

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.