Reputation: 119
I have the following problem trying to deserialize JSON that I read from a file. I always get that it can't be deserialized by object type. What is causing this?
MyModel.cs
public class MyModel
{
public List<toppings> Lista { get; set; }
}
public class toppings
{
public string description { get; set; }
}
Program.cs
static void Main(string[] args)
{
try
{
string json = File.ReadAllText(@"C:\Users\Ricciardo\Documents\Net Core Practice\Pizza\PizzaRead\pizzas.json").ToString();
MyModel objetos = JsonSerializer.Deserialize<MyModel>(json);
foreach (var ingrediente in objetos.Lista)
{
Console.WriteLine(ingrediente.description.ToString());
}
}
catch (Exception ex)
{
Console.Write(ex.Message.ToString());
throw ex;
}
Console.ReadKey();
}
JSON File
[
{
"toppings": [
"pepperoni"
]
},
{
"toppings": [
"feta cheese"
]
},
{
"toppings": [
"pepperoni"
]
},
{
"toppings": [
"bacon"
]
}
]
Upvotes: 1
Views: 663
Reputation: 23298
Your JSON is an array, where every item has toppings
array of strings. So, the proper model should be something like that (decorated with JsonPropertyName
attribute)
using System.Text.Json;
using System.Text.Json.Serialization;
//rest of code
public class MyModel
{
[JsonPropertyName("toppings")]
public List<string> Toppings { get; set; }
}
And deserialization to List<MyModel>
var result = JsonSerializer.Deserialize<List<MyModel>>(jsonString);
foreach (var item in result)
Console.WriteLine(string.Join(", ", item.Toppings));
It gives you a list with 4 items, where every item is a list with single string inside
Upvotes: 0
Reputation: 646
It appears that your class structure doesn't match your JSON structure.
Your JSON is structured as such:
Define your MyModel (or Pizza) class:
public class Pizza
{
public List<string> Toppings {get; set;}
}
Then update your Program.cs Main method:
static void Main(string[] args)
{
try
{
string json = File.ReadAllText(@"C:\Users\Ricciardo\Documents\Net Core Practice\Pizza\PizzaRead\pizzas.json").ToString();
var objetos = JsonSerializer.Deserialize<List<Pizza>>(json);
foreach (var pizza in objetos)
{
//Console.WriteLine(ingrediente.description.ToString());
// TODO: Manipulate pizza objeto
}
}
catch (Exception ex)
{
Console.Write(ex.Message.ToString());
throw ex;
}
Console.ReadKey();
}
You may have to tweak with the casing a little.
Also, a side note the way the JSON is structured poses some problems.
A structure similar to this may help you out more:
[
{
"Toppings": [
{
"name":"pepperoni"
"description":"blah"
},
]
},
]
Then you could actually define a Topping class like so:
public class Topping
{
public string Name {get; set;}
public string Description {get; set;}
}
And change up the Pizza class (MyModel):
public class Pizza
{
public List<Topping> Toppings {get; set;}
}
Upvotes: 2