1

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"
    ]
  }
]

3
  • 1
    It appears that your JSON file contains an array of objects that have another array of toppings inside of each object. You may not be mapping the classes properly. Commented Jun 10, 2020 at 0:08
  • Not may not.. definitely are not. Commented Jun 10, 2020 at 0:08
  • I posted an answer, it's a JSON > Class mapping issue. Hopefully, my answer gives you enough info to take the next steps =) Commented Jun 10, 2020 at 0:21

2 Answers 2

2

It appears that your class structure doesn't match your JSON structure.

Your JSON is structured as such:

  • Array
    • Object
      • Array (toppings)

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

1 Comment

Hi, thanks for your response. I cannot change the json data source. This is how it is structured. Try what you sent me but it doesn't work :(
0

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

2 Comments

Esta es la solución, funciona a la perfección. Te lo agradezco muchisimo. un abrazo
@DanielLazarte Sorry, I don't know Spanish:) But welcome, glad to help

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.