I'm doing some LINQ exercises, where I have to do some queries on a .json file . I need it to show Manufacturers and Models that are the color "Fuscia".
Json format:
{"id":1,"Maker":"Mercedes-Benz","Model":"SL-Class","Year":null,"Color":null,"Location":{"Latitude":null,"Longitude":null}}
I have created a class to be able to pass to List<>
this .json, looking like this:
class Cars
{
public string Maker { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public string Color { get; set; }
public double Location { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
}
In the main
I call and create the List<>
as follows:
string archivoJ = File.ReadAllText("Cars.json"); //Cargamos el archivo.
List<Cars> coches = JsonConvert.DeserializeObject<List<Cars>>(archivoJ); //Creamos una lista con el json.
And in my method where I must execute the Query:
static void Ejer4(List<Cars> lc)
{
var fm = lc.Where(x => x.Color == "Fuscia").Select( y => new { Fabricante = y.Maker, Modelo = y.Model });
foreach(var i in fm)
{
Console.WriteLine($"Fabricante: {i.Fabricante} Modelo: {i.Modelo}");
}
}
But when executing, I get the following exception, marking the position of JasonConvert
:
Newtonsoft.Json.JsonSerializationException: 'Error converting value {null} to type 'System.Int32'. Path '[0].Year', line 1, position 63.'
In the class Cars
I have tried to change the data types to string
all, but it is still the same. How can I prevent it from converting the types null
?
The error is clear and concise, maybe you don't understand it because it is in English, I translate it:
Your JSON has only one line, position 63 is:
The error is obvious: Cannot convert value
null
(which is in position 63) to an integer (which is what a year is supposed to be).You can configure the Newtonsoft deserializer to ignore null values by creating a configuration object:
And provide it to the deserializer:
Optionally, you could have made the year nullable :
But the most appropriate thing is that you sanitize your input data: A year cannot be null in this context.