c# Parsing json to object - c#

I need some help to parse the json rest from IsThereASale API to a c# object but I got stuck because of the json layout:
https://del.dog/orfelefane.json
What I need here is the info from the data array.
Here is how i get the json response:
var client = new RestClient("https://api.isthereanydeal.com/");
client.UseNewtonsoftJson();
var request = new RestRequest("https://api.isthereanydeal.com/v01/deals/list/?key=" + Config.apiKey + "&sort=time");
var json = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content);
As you can notice above I've tried to convert it to a dictionary, but with no success.

You can use online converter for this
public partial class Orfelefane
{
public Meta Meta { get; set; }
public Data Data { get; set; }
}
public partial class Data
{
public long Count { get; set; }
public List<List> List { get; set; }
public DataUrls Urls { get; set; }
}
public partial class List
{
public string Plain { get; set; }
public string Title { get; set; }
public double PriceNew { get; set; }
public double PriceOld { get; set; }
public long PriceCut { get; set; }
public long Added { get; set; }
public long? Expiry { get; set; }
public Shop Shop { get; set; }
public List<Drm> Drm { get; set; }
public ListUrls Urls { get; set; }
}
public partial class Shop
{
public Id Id { get; set; }
public Name Name { get; set; }
}
public partial class ListUrls
{
public Uri Buy { get; set; }
public Uri Game { get; set; }
}
public partial class DataUrls
{
public Uri Deals { get; set; }
}
public partial class Meta
{
public string Currency { get; set; }
}
public enum Drm { DrmFree, Steam };
public enum Id { Bundlestars, Gog, Itchio, Steam };
public enum Name { Fanatical, Gog, ItchIo, Steam };
lastly
var json = JsonConvert.DeserializeObject<Orfelefane>(response.Content);
EDIT:
If your json is not stronglytyped, I suggest you to use
var json = JsonConvert.DeserializeObject<dynamic>(response.Content);
If only the specific part of your json is not static then you can replace that part with dynamic
let say that the content of the List is dynamic inside data, then change
public partial class Data
{
public long Count { get; set; }
public List<List> List { get; set; }
public DataUrls Urls { get; set; }
}
to
public partial class Data
{
public long Count { get; set; }
//OR public dynamic List {get; set;}
public List<dynamic> List { get; set; }
public DataUrls Urls { get; set; }
}

Related

How to process a json response from an API in C#

I've read and reread articles online on how to do this, but it's probably something simple. I'm trying to learn how to process a json response from an API call. I have a simple method I call from Main()
public async void apiTestCall()
{
var httpCall = new HttpClient();
var uri = new Uri("https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&page=2&api_key=DEMO_KEY");
var result = new DataModel();
var response = await httpCall.GetStringAsync(uri);
result = JsonSerializer.Deserialize<DataModel>(response);
I am expecting "result" to be a DataModel object with the data populated. Right now, there is nothing.
Here is the DataModel class
using System.Collections.Generic;
namespace APITestProject
{
class DataModel
{
public class Camera
{
public int id { get; set; }
public string name { get; set; }
public int rover_id { get; set; }
public string full_name { get; set; }
}
public class Rover
{
public int id { get; set; }
public string name { get; set; }
public string landing_date { get; set; }
public string launch_date { get; set; }
public string status { get; set; }
}
public class Photo
{
public int id { get; set; }
public int sol { get; set; }
public Camera camera { get; set; }
public string img_src { get; set; }
public string earth_date { get; set; }
public Rover rover { get; set; }
}
public class Example
{
public IList<Photo> photos { get; set; }
}
}
}
Any suggestions would be greatly appreciated.
Edit #1: Here is the first 3 entries in the json. I didn't want to post the whole thing but the URL is valid for anyone to run and see the response.
{"photos":[{"id":424926,"sol":1000,"camera":{"id":22,"name":"MAST","rover_id":5,"full_name":"Mast Camera"},"img_src":"http://mars.jpl.nasa.gov/msl-raw-images/msss/01000/mcam/1000ML0044631200305217E01_DXXX.jpg","earth_date":"2015-05-30","rover":{"id":5,"name":"Curiosity","landing_date":"2012-08-06","launch_date":"2011-11-26","status":"active"}},{"id":424927,"sol":1000,"camera":{"id":22,"name":"MAST","rover_id":5,"full_name":"Mast Camera"},"img_src":"http://mars.jpl.nasa.gov/msl-raw-images/msss/01000/mcam/1000MR0044631190503679E04_DXXX.jpg","earth_date":"2015-05-30","rover":
Edit #2: I made some changes based on the comments so far and I used the Paste > Special > JSON as Classes and removed the "wrapper" class. Now I get the populated object. FYI, here is the new class VS generated:
namespace APITestProject
{
public class DataModel
{
public Photo[] photos { get; set; }
}
public class Photo
{
public int id { get; set; }
public int sol { get; set; }
public Camera camera { get; set; }
public string img_src { get; set; }
public string earth_date { get; set; }
public Rover rover { get; set; }
}
public class Camera
{
public int id { get; set; }
public string name { get; set; }
public int rover_id { get; set; }
public string full_name { get; set; }
}
public class Rover
{
public int id { get; set; }
public string name { get; set; }
public string landing_date { get; set; }
public string launch_date { get; set; }
public string status { get; set; }
}
}
Can you try the following amendment
var result = JsonSerializer.Deserialize<DataModel.Example>(response);
as it looks like DataModel.Example is actually the class that you are trying to deserialize to based on the response that comes from the following call -
https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&page=2&api_key=DEMO_KEY
i.e. It returns an object containing an array of photo objects as you have defined them. As someone else mentioned, no need to encapsulate all of these classes within another class.
You class DataModel just defines other classes, but do not instance them.
According to the data inside the response, you DataModel class should have at least Photos member. It could be type of List<Photo>
class DataModel {
...
public List<Photo> Photos { get; set; }
}
The Photos definition says, that there is some list of photos of Photo type to be expected.

How do I deserialize JSON correctly in C#

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; }
}

Deserializing a nested JSON string, cannot access properties

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.

What is the right C# structure to deserialize this json into?

I am getting json back from an http and I am trying to deserialized it into a C# object and it keeps coming back as null so my guess is that my data structure is off. Here is my code:
results = httpClient.GetStringAsync(url).Result;
var restResponse = new RestSharp.RestResponse();
restResponse.Content = results;
var deserializer = new JsonDeserializer();
var page = _deserializer.Deserialize<Tree>(restResponse);
Here is the Json:
{
"page":{
"results":[
{
"id":"144111690",
"type":"page",
"status":"current",
"title":"Title 1"
},
{
"id":"157540319",
"type":"page",
"status":"current",
"title":"Title 2"
},
{
"id":"144082624",
"type":"page",
"status":"current",
"title":"Title 3"
}
],
"start":0,
"limit":25,
"size":14
}
}
and Here are my C# objects:
public class Tree
{
public Results page { get; set; }
}
public class Results
{
public ResultDetails results { get; set; }
}
public class ResultDetails
{
public List<PageInfo> Pages { get; set; }
}
public class PageInfo
{
public long id { get; set; }
public string type { get; set; }
public string status { get; set; }
public string title { get; set; }
}
Can anyone advise on what is not "lining up" here?
Why don't you directly create class structure by using Visual studio ..that will give you class structure matching with your json.
you can check here how to generate : Visual Studio Generate Class From JSON or XML
Copy you json >> visual studio Edit menu > Paste Special >> Paste Json as class
This will work:
public class Tree
{
public Page page { get; set; }
}
public class Page
{
public List<Result> results { get; set; }
public int start { get; set; }
public int limit { get; set; }
public int size { get; set; }
}
public class Result
{
public string id { get; set; }
public string type { get; set; }
public string status { get; set; }
public string title { get; set; }
}
results is an array in JSON, but you defined it as an object (ResultDetails)
This might do the trick for you
public class Rootobject
{
[JsonProperty("page")]
public Page page { get; set; }
}
public class Page
{
[JsonProperty("results")]
public Result[] results { get; set; }
[JsonProperty("start")]
public int start { get; set; }
[JsonProperty("limit")]
public int limit { get; set; }
[JsonProperty("size")]
public int size { get; set; }
}
public class Result
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("type")]
public string type { get; set; }
[JsonProperty("status")]
public string status { get; set; }
[JsonProperty("title")]
public string title { get; set; }
}
And the implementation should be
results = httpClient.GetStringAsync(url).Result;
var restResponse = new RestSharp.RestResponse();
restResponse.Content = results;
var deserializer = new JsonDeserializer();
var page = _deserializer.Deserialize<Rootobject>(restResponse);

JSON.NET Resolving Nested Data Types

I'm new to JSON.NET, and I've been playing with the new Marvel API that was recently released.
When I call this API it will return the following JSON Data Structure:-
{
"code": 200,
"status": "Ok",
"etag": "f0fbae65eb2f8f28bdeea0a29be8749a4e67acb3",
"data":
{
"offset": 0,
"limit": 20,
"total": 30920,
"count": 20,
"results": [{array of objects}}]
}
}
I can create Classes for this Data like this :
public class Rootobject
{
public int code { get; set; }
public string status { get; set; }
public string etag { get; set; }
public Data data { get; set; }
}
public class Data
{
public int offset { get; set; }
public int limit { get; set; }
public int total { get; set; }
public int count { get; set; }
public Result[] results { get; set; }
}
public class Result
{
}
Now, my issue. The Results that come back from the API can relate to different Objects, it could be results relating to Characters, Comics, Series etc. The objects all hold different properties.
I need to be able to swap out the Result Class properties based on the Entity Type that the results relate too?
Can this actually be done?
You can use var jObj = JObject.Parse(jsonString) then discover what object type it is by which properties are available on the object.
jObj["someComicSpecificProperty"] != null
However this is not full proof and will need to be done on a per object basis for the results array.
An alternate approach I have seen people use is to have a property on the object that is "typeName".
However the root cause of this problem is that you are trying to strongly type a property that is not strongly typed. I would really recommend splitting these different types of results out into different properties so that you don't have this problem.
As promised, I've posted the anser to this problem. It turns out that the JSON response has nested data covering all related data-types, very much like a relational database.
I found something really cool, I basically made a request to the API and converted its response to a string. I then used the debugger to take a copy of the contents to the clipboard.
I created a new Class and Called it MarvelResponse.
I added the NewtonSoft.Json directive to the file, and used the Paste Special option from Edit Menu in VS2012. Here you can paste the option "Paste as JSON CLasses".
After some minor tweaking here is what it provided :-
namespace Kaiser.Training.Data.JSONClasses
{
public class MarvelResponse
{
public int code { get; set; }
public string status { get; set; }
public string etag { get; set; }
public Data data { get; set; }
}
public class Data
{
public int offset { get; set; }
public int limit { get; set; }
public int total { get; set; }
public int count { get; set; }
public Result[] results { get; set; }
}
public class Result
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public DateTime modified { get; set; }
public Thumbnail thumbnail { get; set; }
public string resourceURI { get; set; }
public Comics comics { get; set; }
public Series series { get; set; }
public Stories stories { get; set; }
public Events events { get; set; }
public Url[] urls { get; set; }
}
public class Thumbnail
{
public string path { get; set; }
public string extension { get; set; }
}
public class Comics
{
public int available { get; set; }
public string collectionURI { get; set; }
public ComicResourceUriItem[] items { get; set; }
public int returned { get; set; }
}
public class ComicResourceUriItem
{
public string resourceURI { get; set; }
public string name { get; set; }
}
public class Series
{
public int available { get; set; }
public string collectionURI { get; set; }
public SeriesResourceItem[] items { get; set; }
public int returned { get; set; }
}
public class SeriesResourceItem
{
public string resourceURI { get; set; }
public string name { get; set; }
}
public class Stories
{
public int available { get; set; }
public string collectionURI { get; set; }
public StoriesResourceItem[] items { get; set; }
public int returned { get; set; }
}
public class StoriesResourceItem
{
public string resourceURI { get; set; }
public string name { get; set; }
public string type { get; set; }
}
public class Events
{
public int available { get; set; }
public string collectionURI { get; set; }
public EventsResourceUriItem[] items { get; set; }
public int returned { get; set; }
}
public class EventsResourceUriItem
{
public string resourceURI { get; set; }
public string name { get; set; }
}
public class Url
{
public string type { get; set; }
public string url { get; set; }
}
}
This was a huge help! Hope someone else finds it useful.

Categories

Resources