I am new to JSON string handling in C# and have the following error when trying to deserialize a JSON string:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Formula1Info.Models.clsMRData]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'MRData.xmlns', line 1, position 19.
The JSON string is:
{"MRData":{"xmlns":"http:\/\/ergast.com\/mrd\/1.5","series":"f1","url":"http://ergast.com/api/f1/1952.json","limit":"30","offset":"0","total":"8","RaceTable":{"season":"1952","Races":[{"season":"1952","round":"1","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Swiss_Grand_Prix","raceName":"Swiss Grand Prix","Circuit":{"circuitId":"bremgarten","url":"http:\/\/en.wikipedia.org\/wiki\/Circuit_Bremgarten","circuitName":"Circuit Bremgarten","Location":{"lat":"46.9589","long":"7.40194","locality":"Bern","country":"Switzerland"}},"date":"1952-05-18"},{"season":"1952","round":"2","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Indianapolis_500","raceName":"Indianapolis 500","Circuit":{"circuitId":"indianapolis","url":"http:\/\/en.wikipedia.org\/wiki\/Indianapolis_Motor_Speedway","circuitName":"Indianapolis Motor Speedway","Location":{"lat":"39.795","long":"-86.2347","locality":"Indianapolis","country":"USA"}},"date":"1952-05-30"},{"season":"1952","round":"3","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Belgian_Grand_Prix","raceName":"Belgian Grand Prix","Circuit":{"circuitId":"spa","url":"http:\/\/en.wikipedia.org\/wiki\/Circuit_de_Spa-Francorchamps","circuitName":"Circuit de Spa-Francorchamps","Location":{"lat":"50.4372","long":"5.97139","locality":"Spa","country":"Belgium"}},"date":"1952-06-22"},{"season":"1952","round":"4","url":"http:\/\/en.wikipedia.org\/wiki\/1952_French_Grand_Prix","raceName":"French Grand Prix","Circuit":{"circuitId":"essarts","url":"http:\/\/en.wikipedia.org\/wiki\/Rouen-Les-Essarts","circuitName":"Rouen-Les-Essarts","Location":{"lat":"49.3306","long":"1.00458","locality":"Rouen","country":"France"}},"date":"1952-07-06"},{"season":"1952","round":"5","url":"http:\/\/en.wikipedia.org\/wiki\/1952_British_Grand_Prix","raceName":"British Grand Prix","Circuit":{"circuitId":"silverstone","url":"http:\/\/en.wikipedia.org\/wiki\/Silverstone_Circuit","circuitName":"Silverstone Circuit","Location":{"lat":"52.0786","long":"-1.01694","locality":"Silverstone","country":"UK"}},"date":"1952-07-19"},{"season":"1952","round":"6","url":"http:\/\/en.wikipedia.org\/wiki\/1952_German_Grand_Prix","raceName":"German Grand Prix","Circuit":{"circuitId":"nurburgring","url":"http:\/\/en.wikipedia.org\/wiki\/N%C3%BCrburgring","circuitName":"Nürburgring","Location":{"lat":"50.3356","long":"6.9475","locality":"Nürburg","country":"Germany"}},"date":"1952-08-03"},{"season":"1952","round":"7","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Dutch_Grand_Prix","raceName":"Dutch Grand Prix","Circuit":{"circuitId":"zandvoort","url":"http:\/\/en.wikipedia.org\/wiki\/Circuit_Zandvoort","circuitName":"Circuit Park Zandvoort","Location":{"lat":"52.3888","long":"4.54092","locality":"Zandvoort","country":"Netherlands"}},"date":"1952-08-17"},{"season":"1952","round":"8","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Italian_Grand_Prix","raceName":"Italian Grand Prix","Circuit":{"circuitId":"monza","url":"http:\/\/en.wikipedia.org\/wiki\/Autodromo_Nazionale_Monza","circuitName":"Autodromo Nazionale di Monza","Location":{"lat":"45.6156","long":"9.28111","locality":"Monza","country":"Italy"}},"date":"1952-09-07"}]}}}
and I deserialize this via this code:
var jF1Season = JsonConvert.DeserializeObject<Root>(strJSON);
The class structure is:
public class Root
{
public List<clsMRData> MRData { get; set; }
}
public class clsMRData
{
public string xmlns { get; set; }
public string series { get; set; }
public string url { get; set; }
public string limit { get; set; }
public string offset { get; set; }
public string total { get; set; }
public List<clsRaceTable> RaceTable { get; set; }
}
public class clsRaceTable
{
public string season { get; set; }
public List<clsRace> Races { get; set; }
}
public class clsRace
{
public string season { get; set; }
public string round { get; set; }
public string url { get; set; }
public string raceName { get; set; }
public List<clsCircuit> Circuit { get; set; }
public string date { get; set; }
public string time { get; set; }
}
public class clsCircuit
{
public string circuitId { get; set; }
public string url { get; set; }
public string circuitName { get; set; }
public List<clsLocation> Location { get; set; }
}
public class clsLocation
{
public string lat { get; set; }
[JsonProperty(PropertyName = "Root.MRData.RaceTable.Races.Circuit.Location.long")]
public string lon { get; set; }
public string locality { get; set; }
public string country { get; set; }
}
I guess the error is relating to how I have set this structure up, but cannot see why, so any help in solving this error would be appreciated.
you have several bugs in your code.Replace List<clsRaceTable> , List<clsCircuit> , List<clsLocation> with clsRaceTable,clsCircuit and clsLocation. Your classes should be
public class Root
{
public clsMRData MRData { get; set; }
}
public class clsMRData
{
public string xmlns { get; set; }
public string series { get; set; }
public string url { get; set; }
public string limit { get; set; }
public string offset { get; set; }
public string total { get; set; }
public clsRaceTable RaceTable { get; set; }
}
public class clsRaceTable
{
public string season { get; set; }
public List<clsRace> Races { get; set; }
}
public class clsRace
{
public string season { get; set; }
public string round { get; set; }
public string url { get; set; }
public string raceName { get; set; }
public clsCircuit Circuit { get; set; }
public string date { get; set; }
public string time { get; set; }
}
public class clsCircuit
{
public string circuitId { get; set; }
public string url { get; set; }
public string circuitName { get; set; }
public clsLocation Location { get; set; }
}
public class clsLocation
{
public string lat { get; set; }
[JsonProperty(PropertyName = "long")]
public string lon { get; set; }
public string locality { get; set; }
public string country { get; set; }
}
I am trying to deserialize the Supreme New York JSON but I am getting an error.
I used json2csharp.com to convert the Json into classes.
Then I summarised them all into one called items
namespace SUPBOTTESTING
{
public class items
{
public string name { get; set; }
public int id { get; set; }
public string image_url { get; set; }
public string image_url_hi { get; set; }
public int price { get; set; }
public int sale_price { get; set; }
public bool new_item { get; set; }
public int position { get; set; }
public string category_name { get; set; }
public int price_euro { get; set; }
public int sale_price_euro { get; set; }
}
}
using System;
using System.Net;
using System.Web.Script.Serialization;
namespace SUPBOTTESTING
{
class Program
{
public static void Main()
{
{
string shop_json = new WebClient().DownloadString("https://www.supremenewyork.com/mobile_stock.json");
JavaScriptSerializer shop_object = new JavaScriptSerializer();
items[] shirt_stock = shop_object.Deserialize<items[]>(shop_json);
Console.WriteLine(shirt_stock[1]);
}
}
}
}
I am getting the error:
Default constructor not found for type SUPBOTTESTING.items[]
Ok here is the solution. You have the correct idea but you need to understand the structure of your Json data.
You are deserializing it into an array of Object whereas your Json data returned itself is not an Array or a List. It contains child nodes that are an array so you need to structure your Object accordingly to get a successful breakdown of data.
Here I have used Newtonsoft to deserialise the Json data into an Object.
I have tested the code and it returns a list of Shirts
static void Main(string[] args)
{
var shop_json = new WebClient().DownloadString("https://www.supremenewyork.com/mobile_stock.json");
var shirt_stock = JsonConvert.DeserializeObject<StockObject>(shop_json);
// Picking shirts to demonstrate how to display values for all shirts
var shirts = shirt_stock.products_and_categories.Shirts;
foreach (var shirt in shirts)
{
var shirtBuilder = new StringBuilder();
shirtBuilder.AppendLine($"Name: {shirt.name}");
shirtBuilder.AppendLine($"ID: {shirt.id.ToString()}");
shirtBuilder.AppendLine($"New Item: {shirt.new_item.ToString()}");
shirtBuilder.AppendLine($"Category Name: {shirt.category_name}");
Console.WriteLine(shirtBuilder);
}
}
public class StockObject
{
public ProductsCats Products_and_categories { get; set; }
}
public class ProductsCats
{
public Details[] Shirts { get; set; }
public Details[] Bags { get; set; }
public Details[] Accessories { get; set; }
public Details[] Pants { get; set; }
public Details[] Jackets { get; set; }
public Details[] Skates { get; set; }
public Details[] Hats { get; set;}
public Details[] Sweatshirts { get; set;}
[JsonProperty("Tops/Sweaters")]
public Details[] TopsSweaters { get;set;}
public Details[] New { get; set; }
}
public class Details
{
public string name { get; set; }
public int id { get; set; }
public string image_url { get; set; }
public string image_url_hi { get; set; }
public int price { get; set; }
public int sale_price { get; set; }
public bool new_item { get; set; }
public int position { get; set; }
public string category_name { get; set; }
public int price_euro { get; set; }
public int sale_price_euro { get; set; }
}
You see what I have done here?
So your Json data contains a parent node products_and_categories and its child node contains an array of Shirts which is what you are after?
StockObject class contains the Parent property called Products_and_categories of type object ProductsCats.
ProductsCats Object contains the property Shirts of type Details which is an array and will be used during the deserialising process.
Hope this helps?
Well you do not need to specify a default constructor. What is wrong is, i think you didn't check the json data properly. Because your items class is not in the first level of json. You need to create a couple of classes to be more accurate on deserializing.
First of all you need to know that this json file has a lot of bad-smells and bad-practices on it.
Note that you need to install Newtonsoft.Json before going further. It is much more convenient way to deserialize a json into C# classes.
Yet, i wrote a proper way of deserializing it:
public class BaseItem
{
public string Name { get; set; }
public int Id { get; set; }
public string Image_url { get; set; }
public string Image_url_hi { get; set; }
public int Price { get; set; }
public int Sale_price { get; set; }
public bool New_item { get; set; }
public int Position { get; set; }
public string Category_name { get; set; }
public int Price_euro { get; set; }
public int Sale_price_euro { get; set; }
}
public class Shirt : BaseItem { }
public class Bag : BaseItem { }
public class Accessory : BaseItem { }
public class Pant : BaseItem { }
public class Jacket : BaseItem { }
public class Skate : BaseItem { }
public class Hat : BaseItem { }
public class Sweatshirt : BaseItem { }
public class TopsSweater : BaseItem { }
public class New : BaseItem { }
public class RootObject
{
public List<object> Unique_image_url_prefixes { get; set; }
public ProductsAndCategories Products_and_categories { get; set; }
public string Release_date { get; set; }
public string Release_week { get; set; }
}
public class ProductsAndCategories
{
public List<Shirt> Shirts { get; set; }
public List<Bag> Bags { get; set; }
public List<Accessory> Accessories { get; set; }
public List<Pant> Pants { get; set; }
public List<Jacket> Jackets { get; set; }
public List<Skate> Skate { get; set; }
public List<Hat> Hats { get; set; }
public List<Sweatshirt> Sweatshirts { get; set; }
[JsonProperty("Tops/Sweaters")]
public List<TopsSweater> TopsSweaters { get; set; }
public List<New> New { get; set; }
}
First of all, all of your items are have the same properties on them, yet, they all marked as different properties. So that, i created a BaseItem class and other empty classes which are inherited from that.
Also you need other 2 classes -which are RootObject and ProductsAndCategories- to provide data on them. Note that there is a JsonProperty("blabla") on the TopsSweaters property. Because, in json file it is Tops/Sweaters, and you can not use that name on a C# property. That is the attribute for using that kind of different property names.
Then you can populate your object like this:
static void Main(string[] args)
{
var jsonData = "https://www.supremenewyork.com/mobile_stock.json";
string shopJson = new WebClient().DownloadString(jsonData);
RootObject shirtStock = JsonConvert.DeserializeObject<RootObject>(shopJson); //All json data is in this variable
Console.WriteLine(shirtStock.Products_and_categories.Shirts[1]);
}
Your problem is that youre using a class to load the JSON data in, where you should use a struct, alternatively you can also create a constructor that takes no arguments and sets all variables to default values, which is a lot of work so just replace class with struct:
public struct Items
{
public string Name { get; set; }
public int Id { get; set; }
public string Image_Url { get; set; }
public string Image_Url_Hi { get; set; }
public int Price { get; set; }
public int Sale_Price { get; set; }
public bool New_item { get; set; }
public int Position { get; set; }
public string Category_Name { get; set; }
public int Price_Euro { get; set; }
public int Sale_Price_Euro { get; set; }
}
Also please stick to C# naming conventions, you should be able to do this since most JSON parsers are case insensitive by default.
Some more info: A class doesnt really has a proper default constructor if you dont define one, where as a struct always has a default constructor, so when the JSON parser wants to init your class it cant because a default constructor isnt definded.
static void Main(string[] args)
{
string shop_json = new WebClient().DownloadString("https://www.supremenewyork.com/mobile_stock.json");
JavaScriptSerializer shop_object = new JavaScriptSerializer();
var shirt_stock = shop_object.Deserialize<NewYarkItems>(shop_json);
var v = shirt_stock;
}
public class NewYarkItems
{
public dynamic unique_image_url_prefixes { get; set; }
public products_and_categories products_And_Categories { get; set; }
public string release_date { get; set; }
public string release_week { get; set; }
}
public class products_and_categories
{
public List<items> Jackets { get; set; }
}
public class items
{
public string name { get; set; }
public int id { get; set; }
public string image_url { get; set; }
public string image_url_hi { get; set; }
public int price { get; set; }
public int sale_price { get; set; }
public bool new_item { get; set; }
public int position { get; set; }
public string category_name { get; set; }
public int price_euro { get; set; }
public int sale_price_euro { get; set; }
}
I am having issues deserializing a nested JSON array from the Genius lyric website API. I formulated the object using http://json2csharp.com. When I deserialize the object, I am unable to access the properties inside of the class, which wasn't entirely unexpected, I am just not sure how to properly design an actual solution to the problem. The JSON object conversions work fine when they are not nested.
What would be the best way to go about handling this?
Here is the conversion code:
string test = await G.SearchGeniusASync(textBox1.Text);
var data = JsonConvert.DeserializeObject<GeniusApiObject>(test);
Here is my class:
class GeniusApiObject
{
public class Meta
{
public int status { get; set; }
}
public class Stats
{
public bool hot { get; set; }
public int unreviewed_annotations { get; set; }
public int concurrents { get; set; }
public int pageviews { get; set; }
}
public class PrimaryArtist
{
public string api_path { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public string image_url { get; set; }
public bool is_meme_verified { get; set; }
public bool is_verified { get; set; }
public string name { get; set; }
public string url { get; set; }
public int iq { get; set; }
}
public class Result
{
public int annotation_count { get; set; }
public string api_path { get; set; }
public string full_title { get; set; }
public string header_image_thumbnail_url { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public int lyrics_owner_id { get; set; }
public string lyrics_state { get; set; }
public string path { get; set; }
public int? pyongs_count { get; set; }
public string song_art_image_thumbnail_url { get; set; }
public Stats stats { get; set; }
public string title { get; set; }
public string title_with_featured { get; set; }
public string url { get; set; }
public PrimaryArtist primary_artist { get; set; }
}
public class Hit
{
public List<object> highlights { get; set; }
public string index { get; set; }
public string type { get; set; }
public Result result { get; set; }
}
public class Response
{
public List<Hit> hits { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public Response response { get; set; }
}
}
This is the source for the SearchGeniusASync method in case it is helpful:
public async Task<string>SearchGeniusASync(string searchParameter)
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", clientAccessToken);
var result = await httpClient.GetAsync(new Uri("https://api.genius.com/search?q=" + searchParameter), HttpCompletionOption.ResponseContentRead);
var data = await result.Content.ReadAsStringAsync();
return data;
}
This is the scope I am given access to:
https://i.imgur.com/9mZMvfp.png
Here's a sample JSON request in plaintext:
https://pastebin.com/iA8dQafW
GeniusApiObject is not needed in the code, but I'll leave it in just because it helps organize things (may be that something else also has a RootObject from the auto-generator).
The problem is that you are trying to deserialize to what is just an empty class, the class itself has no properties, so you can't deserialize to it. You need to deserialize to the GeniusApiObject.RootObject.
var data = JsonConvert.DeserializeObject<GeniusApiObject.RootObject>(test);
Will deserialize to the .RootObject subclass. This is verified working:
Where I'm using File.ReadAllText("test.json") to load the example API data provided.
Here is a .NET Fiddle showing it working (without the root object and only one song in the response). Thanks to #maccttura.
This is my code:
dynamic resultObject = JsonConvert.DeserializeObject(Result);
string final = JsonConvert.SerializeObject(resultObject);
This my the result of final (JSON):
How do get the selling_price field? like doing final.selling_price?
My class:
public class ItemPriceJson {
public string item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public string price_level_id { get; set; }
public string price_level_code { get; set; }
public string selling_price { get; set; }
} // itemPriceJson
You're not deserializing the json to a dynamic object properly. First of all, it's an array, not an object.
So, try it like this:
dynamic resultObject = JArray.Parse(Result); //Dynamic object.
var sellingPrice = resultObject[0].selling_price; //Get the selling price. Could also use some casting here.
You should change your class to
public class ItemPriceJson {
public int item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public int price_level_id { get; set; }
public string price_level_code { get; set; }
public int selling_price { get; set; }
} // itemPriceJson
and deserialize it with
var results = JsonConvert.DeserializeObject<List<ItemPriceJson>>( Result );
because the json result contains an array of objects and so you need a collection for deserialization
Create a POCO class which describes the object for example;
public class MyItemObject
{
public string item_price_id { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
}
Then use JsonConvert to deserialize a instance of the object.
var result = JsonConvert.DeserializeObject<MyItemObject>(json);
EDIT
As json is a list/collection deserialize as a list type;
var listResult = JsonConvert.DeserializeObject<List<MyItemObject>>(json);
public class ItemPriceJson {
public string item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public string price_level_id { get; set; }
public string price_level_code { get; set; }
public string selling_price { get; set; }
}
And you can use the Newtonsoft json library
var result = JsonConvert.DeserializeObject<List<ItemPriceJson>>(jsonstring);
I have the result of an API call which looks like:
{"Operations":[{"OperationId":"2","OperationObjectId":"Application","OperationName":"UnlockSession","OperationParameters":[{"Name":"viewModel","Value":"model"},{"Name":"returnUrl","Value":"https://"}],"OperationCaller":{"UserPrincipalName":"bob","ClientIPAddress":""},"OperationResult":"Succeeded","OperationStatus":200,"OperationRequest":{"Method":"POST","Url":""},"OperationStartedTime":"2013-08-20T12:04:17.5462357Z","OperationCompletedTime":"2013-08-20T12:04:17.9979469Z"}],"ContinuationToken":null}
Ideally I want to convert it to an object so I can do stuff like:
object.OperationObjectID; // gives Application
object.Method; // gives POST
object.OperationResult; // gives Succeeded
Does any one know how that is done? Does the JSON parse need to be aware of the format?
Thanks,
Andrew
you can use Json.Net as below
dynamic object = JObject.Parse(yorjsonstring);
object.Operations[0].OperationObjectID;
object.Operations[0].Method;
object.Operations[0].OperationResult;
rather than using dynamic object you can generate classes for your json and serialize to those classes like below.
you can get help of http://json2csharp.com/ site for generate classes
public class OperationParameter
{
public string Name { get; set; }
public string Value { get; set; }
}
public class OperationCaller
{
public string UserPrincipalName { get; set; }
public string ClientIPAddress { get; set; }
}
public class OperationRequest
{
public string Method { get; set; }
public string Url { get; set; }
}
public class Operation
{
public string OperationId { get; set; }
public string OperationObjectId { get; set; }
public string OperationName { get; set; }
public List<OperationParameter> OperationParameters { get; set; }
public OperationCaller OperationCaller { get; set; }
public string OperationResult { get; set; }
public int OperationStatus { get; set; }
public OperationRequest OperationRequest { get; set; }
public string OperationStartedTime { get; set; }
public string OperationCompletedTime { get; set; }
}
public class RootObject
{
public List<Operation> Operations { get; set; }
public object ContinuationToken { get; set; }
}
then
RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonstring);
obj.Operations[0].OperationObjectID;
Try to use JavaScriptSerializer class: http://msdn.microsoft.com/ru-ru/library/system.web.script.serialization.javascriptserializer.aspx.