so I am trying to convert a JSON string to a list of objects that I made myself but for some reasons it keeps throwing me errors and after googling it I couldn't find my error.
Here is what throws the error. (I already tried using a list instead of an array and it still made an exception).
items[] items = JsonSerializer.Deserialize<items[]>(h.Content.ReadAsStringAsync().Result);
This is the exception I'm getting:
"The JSON value could not be converted to Scraper.items[]. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
Here is what my object item looks like looks like :
public Int64 id;
public string title;
public double price;
public string currency;
public string brand_title;
public string size_title;
public user user;
public bool is_for_swap;
public string url;
public bool promoted;
public photo photo;
public int favorit_count;
public bool is_favorite;
public string badge;
public string[] conversion;
public int view_count;
(I know I am not doing propreties or any constructor. I deleted them all while trying to solve my issue. (Other objects are also there but I wont show them since I don't think they are the thing making my exceptions and I don't want this post to be unreadable))
My JSON : https://pastebin.com/AZE1AwhL
Thanks for reading this and getting some help would make me progress a lot on my project.
CodePudding user response:
The JSON you have linked is not an array. It's an object, with a property items
which is an array. So JsonSerializer.Deserialize<items[]>
won't work. You need to deserialize to a class with an items
property.
Something like this:
public class Wrapper
{
[JsonProperty("items")]
public Item[] Items { get; set; }
}
// ...
var options = new JsonSerializerOptions { IncludeFields = true };
var wrapper = JsonSerializer.Deserialize<Wrapper>(
h.Content.ReadAsStringAsync().Result,
options);
wrapper.Items // This is your array
Side note: C# naming conventions dictate you should use PascalCasing for class names. So items
should be called Items
or more apropriately Item
since it's not a list type.