Mario Garcia
Mario Garcia

Reputation: 307

Use Json file as db

I am starting c# and I was asked to create a small Api using a given Json file as DB. My json file looks like:

{"Items": [
  {
    "id": 1,
    "name": "Apple",
    "price": 12.50,
    "image": "some url",
    "description": "Some text",
    "tags": [ "fruit", "red" ],
    "category": "fruit"
  },
]}

I created a model:

public class Product
{
  public int ID { get; set; }
  public string Name { get; set; }
  public decimal Price { get; set; }
  public string Image { get; set; }
  public string Description { get; set; }
  public List<Tags> Tags { get; set; }
  public string Category { get; set; }
}

public class Tags
{
  public string Tag { get; set; }
}

And my controller looks like:

[ApiController]
[Route("api/[controller]")]
public class ProductController : Controller
{
  [HttpGet]
  public IEnumerable<Product> Get()
  {
    StreamReader r = new StreamReader("./items.json");
    string jsonString = r.ReadToEnd();
    List<Product> productsList = JsonConvert.DeserializeObject<List<Product>>(jsonString);
    return productsList;
  }
}

The error I get:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Kata.Product]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

As I am new to c#, I am having trouble to find out how to simply return what I have in my Json file. At some point I was able to return the list by changing the json file(not the greatest idea) but all the items were null.

Thank you

Upvotes: 0

Views: 1523

Answers (1)

Serge
Serge

Reputation: 43959

You have a bug in your json classes. You can't use a special class for the tags, try to replace it by string array or list. The same about items. You deserialized the whole Root object, items just a property of this object. So since you don't need the whole object but just list of items, you have to select only them.

 var jsonDeserialized= JsonConvert.DeserializeObject<Root> (jsonString);
List<Product> productsList = jsonDeserialized.Items ;

classes

public class Product
    {
        public int id { get; set; }
        public string name { get; set; }
        public double price { get; set; }
        public string image { get; set; }
        public string description { get; set; }
        public List<string> tags { get; set; }
        public string category { get; set; }
    }

    public class Root
    {
        public List<Product> Items { get; set; }
    }

and fix json

{
    "Items": [{
        "id": 1,
        "name": "Apple",
        "price": 12.50,
        "image": "some url",
        "description": "Some text",
        "tags": ["fruit", "red"],
        "category": "fruit"
    }]
}

Upvotes: 2

Related Questions