Home > Mobile >  InvalidOperationException: Cannot get the value of a token type 'String' as a number
InvalidOperationException: Cannot get the value of a token type 'String' as a number

Time:11-30

Trying to get data from products.json file and store it in Products[] mention in file JsonFileProductServices.cs but getting this error 'The JSON value could not be converted to System.Int32. Path: $[0].id | LineNumber: 2 | BytePositionInLine: 33.'

JsonFileProductServices.cs is basically service to fetch data from product.json

Below mention are the files

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text.Json.Serialization;
using System.Text.Json;

namespace DevTest.Website.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Maker { get; set; }
        [JsonPropertyName("img")]
        public string Image { get; set; }
        public string Url { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public int[] Ratings { get; set; }

        public override string ToString() => JsonSerializer.Serialize<Product>(this);
    }
}
---product.cs---
[
    {
        "id" : "jenlooper-cactus",
        "maker" : "@jenlooper",
        "img" : "https://user-images.githubusercontent.com/41929050/61567048-13938600-aa33-11e9-9cfd-712191013192.jpeg",
        "url" : "https://www.hackster.io/agent-hawking-1/the-quantified-cactus-an-easy-plant-soil-moisture-sensor-e65393",
        "title" : "The Quantified Cactus: An Easy Plant Soil Moisture Sensor",
        "description" : "This project is a good learning project to get comfortable with soldering and programming an Arduino."
    },
    {
        "id" : "jenlooper-light",
        "maker" : "jenlooper",
        "img" : "https://user-images.githubusercontent.com/41929050/61567049-13938600-aa33-11e9-9c69-a4184bf8e524.jpeg",
        "url" : "https://www.hackster.io/agent-hawking-1/book-light-dee7e4",
        "title" : "A beautiful switch-on book light",
        "description" : "Use craft items you have around the house, plus two LEDs and a LilyPad battery holder, to create a useful book light for reading in the dark."
    },
    {
        "id" : "jenlooper-lightshow",
        "maker" : "@jenlooper",
        "img" : "https://user-images.githubusercontent.com/41929050/61567053-13938600-aa33-11e9-9780-104fe4019659.png",
        "url" : "https://www.hackster.io/agent-hawking-1/bling-your-laptop-with-an-internet-connected-light-show-30e4db",
        "title" : "Bling your Laptop with an Internet-Connected Light Show",
        "description" : "Create a web-connected light-strip API controllable from your website, using the Particle.io."
    },
    {
        "id" : "jenlooper-survival",
        "maker" : "jenlooper",
        "img" : "https://user-images.githubusercontent.com/41929050/61567051-13938600-aa33-11e9-8ae7-0b5c19aafab4.jpeg",
        "url" : "https://www.hackster.io/agent-hawking-1/create-a-compact-survival-kit-38bfdb",
        "title" : "Create a Compact Survival Kit with LED Track Lighting",
        "description" : "Use an Altoids tin with Chibitronics sticker LEDs to create a light-up compact that doubles as a survival kit for the young hipster"
    },
    {
        "id" : "sailorhg-bubblesortpic",
        "maker" : "sailorhg",
        "img" : "https://user-images.githubusercontent.com/41929050/61567054-13938600-aa33-11e9-9163-eec98e239b7a.png",
        "url" : "https://twitter.com/sailorhg/status/1090107740049952770",
        "title" : "Bubblesort Visualization",
        "description" : "Visualization of sailor scouts sorted by bubblesort algorithm by their planet's distance from the sun"
    },
    {
        "id" : "sailorhg-corsage",
        "maker" : "sailorhg",
        "img" : "https://user-images.githubusercontent.com/41929050/61567055-142c1c80-aa33-11e9-96ff-9fbac6413625.png",
        "url" : "https://twitter.com/sailorhg/status/1090113666911891456",
        "title" : "Light-up Corsage",
        "description" : "Light-up corsage I made with my summer intern."
    },
    {
        "id" : "sailorhg-kit",
        "maker" : "sailorhg",
        "img" : "https://user-images.githubusercontent.com/41929050/61567056-142c1c80-aa33-11e9-8682-10065d338145.png",
        "url" : "https://twitter.com/sailorhg/status/1090122822007963648",
        "title" : "Pastel hardware kit",
        "description" : "Pastel hardware kits complete with custom manufactured pastel alligator clips."
    },
    {
        "id" : "sailorhg-led",
        "maker" : "sailorhg",
        "img" : "https://user-images.githubusercontent.com/41929050/61567052-13938600-aa33-11e9-9a88-cd842073ba44.jpg",
        "url" : "https://twitter.com/sailorhg/status/1090117277540745216",
        "title" : "Heart-shaped LED",
        "description" : "custom molded heart shaped LED with sprinkles."
    },
    {
        "id" : "selinazawacki-soi-shirt",
        "maker" : "selinazawacki",
        "img" : "https://user-images.githubusercontent.com/41929050/61567060-142c1c80-aa33-11e9-8188-5a4803844a9e.png",
        "url" : "https://www.instagram.com/p/BNvESj-j8PI/",
        "title" : "Black Sweatshirt",
        "description" : "Black sweatshirt hoody with the Sick of the Internet logo."
    },
    {
        "id" : "selinazawacki-soi-pins",
        "maker" : "selinazawacki",
        "img" : "https://user-images.githubusercontent.com/41929050/61567059-142c1c80-aa33-11e9-939b-2ecf4492786d.png",
        "url" : "https://www.instagram.com/p/BNm6hZzDoEF/",
        "title" : "Sick of the Internet Pins",
        "description" : "Still some time to enter the pin/sticker giveaway! "
    },
    {
        "id" : "vogueandcode-hipster-dev-bro",
        "maker" : "vogueandcode",
        "img" : "https://user-images.githubusercontent.com/41929050/61567061-14c4b300-aa33-11e9-9fee-63ff2c0c9823.png",
        "url" : "https://www.vogueandcode.com/shop/hipster-dev-bro",
        "title" : "Hipster Dev",
        "description" : "Hipster Dev is busy coding away while styled in a camo jacket and orange beanie."
    },
    {
        "id" : "vogueandcode-pretty-girls-code-tee",
        "maker" : "vogueandcode",
        "img" : "https://user-images.githubusercontent.com/41929050/61567062-14c4b300-aa33-11e9-9dcd-8bfed4ece810.png",
        "url" : "https://www.vogueandcode.com/shop/pretty-girls-code-tee",
        "title" : "Pretty Girls Code Tee",
        "description" : "Everyone’s favorite design is finally here on a tee! The Pretty Girls Code crew-neck tee is available in a soft pink with red writing."
    },
    {
        "id" : "vogueandcode-ruby-sis-2",
        "maker" : "vogueandcode",
        "img" : "https://user-images.githubusercontent.com/41929050/61567063-14c4b300-aa33-11e9-8515-bcb866da9ea3.png",
        "url" : "https://www.vogueandcode.com/shop/ruby-sis-2",
        "title" : "Ruby Sis",
        "description" : "Styled in a dashiki, Ruby Sis is listening to music while coding in her favorite language, Ruby!"
    },
    {
        "id" : "selinazawacki-moon",
        "maker" : "selinazawacki",
        "img" : "https://user-images.githubusercontent.com/41929050/61567057-142c1c80-aa33-11e9-9781-9e442418eaab.png",
        "url" : "https://www.instagram.com/p/BFktVYPinKQ/",
        "title" : "Holographic Dark Moon Necklace",
        "description" : "Not sure if I'll be making more, get it while I have it in the store."
    },
    {
        "id" : "selinazawacki-shirt",
        "maker" : "selinazawacki",
        "img" : "https://user-images.githubusercontent.com/41929050/61567058-142c1c80-aa33-11e9-89fb-b4f30d84d69d.png",
        "url" : "https://www.instagram.com/p/BEXlpiZCnJ3/",
        "title" : "Floppy Crop",
        "description" : "Used up the Diskette fabric today to make 2 of these crops."
    }
]
----products.json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text.Json.Serialization;
using System.Text.Json;
using Microsoft.AspNetCore.Hosting;
using DevTest.Website.Models;

namespace DevTest.Website.Services
{
    public class JsonFileProductService
    {
        public JsonFileProductService(IWebHostEnvironment webHostEnvironment)
        {
            WebHostEnvironment = webHostEnvironment;
        }

        public IWebHostEnvironment WebHostEnvironment { get; }

        private string JsonFileName => Path.Combine(WebHostEnvironment.WebRootPath, "data", "products.json");

        public IEnumerable<Product> GetProducts()
        {
            using (var jsonFileReader = File.OpenText(JsonFileName))
            {
                return JsonSerializer.Deserialize<Product[]>(jsonFileReader.ReadToEnd(),
                new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });
            }

        }
    }
}
--JsonFileProductService.cs---

CodePudding user response:

How are you going to convert

    "id" : "jenlooper-survival",

to this

public class Product
{
        public int Id { get; set; }
        .....
}

you have to fix the class

public class Product
{
        public string Id { get; set; }
        .....
}

CodePudding user response:

Hard to tell without any source code but potential problems that can cause this:

  • Different model/dto when reading vs writing
  • Data can be serialized as some type T and you try cast it to string or data is as string but you trying to deserialize it to T.

I would compare your json data types to your C# model. If you using JsonSerializer.Deserialize you can try to use JsonConvert.DeserializeObject from Newtonsoft.Json but I would first try to find difference between your model and json file.

  • Related