hey i want to Deserialize this json API response to get values including profile state etc for processing in the program.
i tried multiple ways from different questions in here but i get response as null.
here is the code, correct me what i am doing wrong please
{
"response": {
"players": [{
"steamid": "xxxxxxxxxxxxxxxxx",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "xxxx xxxx",
"lastlogoff": 1529478555,
"commentpermission": 1,
"profileurl": "xxxxxxxxxxxxxxx",
"avatar": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"avatarmedium": "xxxxxxxxxxxxxxxxxxxxx",
"avatarfull": "xxxxxxxxxxx",
"personastate": 1,
"realname": "xxxx",
"primaryclanid": "xxxxxxxxxx",
"timecreated": 1097464215,
"personastateflags": 0
}]
}
}
The code i tried
public class AccountInfo
{
public string steamid { get; set; }
public int communityvisibilitystate { get; set; }
public int profilestate { get; set; }
public string personaname { get; set; }
public ulong lastlogoff { get; set; }
public int commentpermission { get; set; }
public string profileurl { get; set; }
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public int personastate { get; set; }
public string realname { get; set; }
public string primaryclanid { get; set; }
public ulong timecreated { get; set; }
public int personastateflags { get; set; }
}
public class Response
{
public AccountInfo response { get; set; }
}
public class Response1
{
public Response players { get; set; }
}
static void Main(string[] args)
{
DeserilizeJson();
}
internal static void DeserilizeJson()
{
string json = GetUrlToString("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=xxxxxxxxxxxxxxxxxxxxx&steamids=xxxxxxxxxxxxxxx");
Console.WriteLine(json);
Response1 info = JsonConvert.DeserializeObject<Response1>(json);
using (StreamWriter file = File.CreateText(#"c:\test.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, info);
}
}
internal static string GetUrlToString(string url)
{
String Response = null;
try
{
using (WebClient client = new WebClient())
{
Response = client.DownloadString(url);
}
}
catch (Exception)
{
return null;
}
return Response;
}
Use this as a Model Class
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class JsonModel
{
[JsonProperty("response")]
public Response Response { get; set; }
}
public partial class Response
{
[JsonProperty("players")]
public List<Player> Players { get; set; }
}
public partial class Player
{
[JsonProperty("steamid")]
public string Steamid { get; set; }
[JsonProperty("communityvisibilitystate")]
public long Communityvisibilitystate { get; set; }
[JsonProperty("profilestate")]
public long Profilestate { get; set; }
[JsonProperty("personaname")]
public string Personaname { get; set; }
[JsonProperty("lastlogoff")]
public long Lastlogoff { get; set; }
[JsonProperty("commentpermission")]
public long Commentpermission { get; set; }
[JsonProperty("profileurl")]
public string Profileurl { get; set; }
[JsonProperty("avatar")]
public string Avatar { get; set; }
[JsonProperty("avatarmedium")]
public string Avatarmedium { get; set; }
[JsonProperty("avatarfull")]
public string Avatarfull { get; set; }
[JsonProperty("personastate")]
public long Personastate { get; set; }
[JsonProperty("realname")]
public string Realname { get; set; }
[JsonProperty("primaryclanid")]
public string Primaryclanid { get; set; }
[JsonProperty("timecreated")]
public long Timecreated { get; set; }
[JsonProperty("personastateflags")]
public long Personastateflags { get; set; }
}
Then do this in your Main Class
var info = JsonConvert.DeserializeObject<JsonModel>(json);
var Response = info.Response
Open nuget, search newtonsoft.json and install.
Deserialize:
var deserialized = JsonConvert.DeserializeObject(jsonstring);
Try this:
public class Player
{
public string steamid { get; set; }
public int communityvisibilitystate { get; set; }
public int profilestate { get; set; }
public string personaname { get; set; }
public ulong lastlogoff { get; set; }
public int commentpermission { get; set; }
public string profileurl { get; set; }
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public int personastate { get; set; }
public string realname { get; set; }
public string primaryclanid { get; set; }
public ulong timecreated { get; set; }
public int personastateflags { get; set; }
}
public class Response
{
public Player[] players { get; set; }
}
public class EncapsulatedResponse
{
public Response response {get;set;}
}
internal static void DeserilizeJson()
{
string json = GetUrlToString("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=xxxxxxxxxxxxxxxxxxxxx&steamids=xxxxxxxxxxxxxxx");
Console.WriteLine(json);
EncapsulatedResponse info = JsonConvert.DeserializeObject<EncapsulatedResponse>(json);
using (StreamWriter file = File.CreateText(#"c:\test.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, info);
}
}
The players property should be a list of players as it is an array . Below is the Correct Model
public class Player
{
public string steamid { get; set; }
public int communityvisibilitystate { get; set; }
public int profilestate { get; set; }
public string personaname { get; set; }
public int lastlogoff { get; set; }
public int commentpermission { get; set; }
public string profileurl { get; set; }
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public int personastate { get; set; }
public string realname { get; set; }
public string primaryclanid { get; set; }
public int timecreated { get; set; }
public int personastateflags { get; set; }
}
public class Response
{
public List<Player> players { get; set; }
}
You need to change the object structure:
public class Response
{
public AccountInfo[] players { get; set; }
}
public class Response1
{
public Response response { get; set; }
}
then deserialize Response1 (like u do currently)
Just to provide a different approach, you can use JObject (Newtonsoft.Json.Linq) so that you only need the AccountInfo class:
var accounts = JObject.Parse(json).Root
.SelectToken("response.players")
.ToObject(typeof(AccountInfo[]));
Or in some cases, it is even easier just navigating the properties:
var accounts = JObject.Parse(json)["response"]["players"]
.ToObject((typeof(AccountInfo[])));
Related
I'm trying to consume a web API into Blazor but am struggling to extract certain information from the API
using System.Text.Json;
namespace CA3.Song
{
public class SongService : ISongService
{
private readonly HttpClient _httpClient;
const string _baseUrl = "https://genius-song-lyrics1.p.rapidapi.com/";
const string _songEndpoint = "songs/chart?time_period=day&chart_genre=all&per_page=10&page=1";
const string _host = "genius-song-lyrics1.p.rapidapi.com";
const string _key = "{key}";
public SongService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<List<SongItem>> GetSong()
{
Configure();
var response = await _httpClient.GetAsync(_songEndpoint);
var response_outcome = response.EnsureSuccessStatusCode;
using var stream = await response.Content.ReadAsStreamAsync();
var dto = await JsonSerializer.DeserializeAsync<SongDto>(stream);
return dto.response.chart_items.Select(n => new SongItem { Artist = n.item.primary_artist, Title = n.item.primary_title, ReleaseDate = n.primary_release_date }).ToList().T ;
}
private void Configure()
{
_httpClient.BaseAddress = new Uri(_baseUrl);
_httpClient.DefaultRequestHeaders.Add("X-RapidAPI-Host", _host);
_httpClient.DefaultRequestHeaders.Add("X-Rapid-Key", _key);
}
}
}
The issue is on the return statement using LINQ.
namespace CA3.Song
{
public class SongDto
{
public Meta meta { get; set; }
public Response response { get; set; }
}
public class Meta
{
public int status { get; set; }
}
public class Response
{
public Chart_Items[] chart_items { get; set; }
public int next_page { get; set; }
}
public class Chart_Items
{
public string _type { get; set; }
public string type { get; set; }
public Item item { get; set; }
}
public class Item
{
public string _type { get; set; }
public int annotation_count { get; set; }
public string api_path { get; set; }
public string artist_names { 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 bool instrumental { get; set; }
public int lyrics_owner_id { get; set; }
public string lyrics_state { get; set; }
public int lyrics_updated_at { get; set; }
public string path { get; set; }
public int pyongs_count { get; set; }
public string relationships_index_url { get; set; }
public Release_Date_Components release_date_components { get; set; }
public string release_date_for_display { get; set; }
public string song_art_image_thumbnail_url { get; set; }
public string song_art_image_url { get; set; }
public Stats stats { get; set; }
public string title { get; set; }
public string title_with_featured { get; set; }
public int updated_by_human_at { get; set; }
public string url { get; set; }
public Featured_Artists[] featured_artists { get; set; }
public Primary_Artist primary_artist { get; set; }
}
public class Release_Date_Components
{
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
}
public class Stats
{
public int unreviewed_annotations { get; set; }
public int concurrents { get; set; }
public bool hot { get; set; }
public int pageviews { get; set; }
}
public class Primary_Artist
{
public string _type { get; set; }
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 string index_character { get; set; }
public bool is_meme_verified { get; set; }
public bool is_verified { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string url { get; set; }
public int iq { get; set; }
}
public class Featured_Artists
{
public string _type { get; set; }
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 string index_character { get; set; }
public bool is_meme_verified { get; set; }
public bool is_verified { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string url { get; set; }
public int iq { get; set; }
}
}
Above is the JSON file and I'm trying to extract the artist name, song title and release date from Item but it isn't in a list so I'm trying to find a way to extract this info using LINQ. Any help would be greatly appreciated !
I think you misinterpreted the declaration of the JSON. They are stored in an array Chart_Items[] chart_items thus you may use linq.
There are many ways to do this, I took advantage of named tuples in modern C# paired with linq.
Response r = new Response();//some resonse from api
var results = r.chart_items.Select(i => (i.item.artist_names, i.item.title, i.item.release_date_components)).ToList();
foreach(var result in results)
{
string artist_names = result.artist_names;
string title = result.title;
Release_Date_Components release_date_components = result.release_date_components;
}
I faced the problem: Cannot deserialize the current JSON object.
As follows:
public List<Track> Tracks { get; set; }
public async Task<List<Track>> GetTracking()
{
using (var httpClient = new HttpClient())
{
using (var requests = new HttpRequestMessage(new HttpMethod("GET"), "urlxxxxxxxx..."))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
requests.Headers.TryAddWithoutValidation("accept", "application/json");
var response = await httpClient.SendAsync(requests);
using (HttpContent content = response.Content)
{
var jsonStr = content.ReadAsStringAsync().GetAwaiter().GetResult();
var res = JsonConvert.DeserializeObject<List<Track>>(jsonStr); //Get Error**
Tracks = res;
}
}
}
return Tracks;
}
Model Class
public class Track
{
public List<Events> events { get; set; }
}
public class Events
{
public string eventID { get; set; }
public string eventType { get; set; }
public string eventDateTime { get; set; }
public string eventCreatedDateTime { get; set; }
public string eventClassifierCode { get; set; }
public string transportEventTypeCode { get; set; }
public string documentID { get; set; }
public string shipmentEventTypeCode { get; set; }
public List<DocumentReferences> documentReferences { get; set; }
public TransportCall transportCall { get; set; }
}
public class DocumentReferencesMearsk
{
public string documentReferenceType { get; set; }
public string documentReferenceValue { get; set; }
}
public class TransportCallMaersk
{
public string transportCallID { get; set; }
public string carrierServiceCode { get; set; }
public string exportVoyageNumber { get; set; }
public string importVoyageNumber { get; set; }
public int transportCallSequenceNumber { get; set; }
public string UNLocationCode { get; set; }
public string facilityCode { get; set; }
public string facilityCodeListProvider { get; set; }
public string facilityTypeCode { get; set; }
public string otherFacility { get; set; }
public string modeOfTransport { get; set; }
public LocationMearsk location { get; set; }
public VesselMearsk vessel { get; set; }
}
My input data:
https://drive.google.com/file/d/12g0nHkHlmbU4Af8crHlzKXD_ERIZdCyH/view?usp=sharing
As in my description. I get the error: I get the error: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[XX. Models.Track]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Even though I declared: public List events { get; set; }
Is the problem I have misunderstood the format of DeserializeObject. Looking forward to everyone's help. Thank
you have an object, not an array
var res = JsonConvert.DeserializeObject<Track>(jsonStr);
and fix class
public class Events
{
....
public List<DocumentReferencesMearsk> documentReferences { get; set; }
public TransportCallMaersk transportCall { get; set; }
}
Your model is incomplete and has typos. Assuming you have the correct versions of them.
You are doing:
var res = JsonConvert.DeserializeObject<List<Track>>(jsonStr);
which should be just:
var res = JsonConvert.DeserializeObject<Track>(jsonStr);
Your json doesn't have an array at the root level.
Full working sample:
void Main()
{
var res = JsonConvert.DeserializeObject<Track>(myJson);
}
public class Track
{
public List<Events> events { get; set; }
}
public class Events
{
public string eventID { get; set; }
public string eventType { get; set; }
public string eventDateTime { get; set; }
public string eventCreatedDateTime { get; set; }
public string eventClassifierCode { get; set; }
public string transportEventTypeCode { get; set; }
public string documentID { get; set; }
public string shipmentEventTypeCode { get; set; }
public List<DocumentReferencesMearsk> documentReferences { get; set; }
public TransportCallMaersk transportCall { get; set; }
}
public class DocumentReferencesMearsk
{
public string documentReferenceType { get; set; }
public string documentReferenceValue { get; set; }
}
public class TransportCallMaersk
{
public string transportCallID { get; set; }
public string carrierServiceCode { get; set; }
public string exportVoyageNumber { get; set; }
public string importVoyageNumber { get; set; }
public int transportCallSequenceNumber { get; set; }
public string UNLocationCode { get; set; }
public string facilityCode { get; set; }
public string facilityCodeListProvider { get; set; }
public string facilityTypeCode { get; set; }
public string otherFacility { get; set; }
public string modeOfTransport { get; set; }
public Location location { get; set; }
public Vessel vessel { get; set; }
}
public partial class Location
{
public string LocationName { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string UnLocationCode { get; set; }
public string FacilityCode { get; set; }
public string FacilityCodeListProvider { get; set; }
}
public partial class Vessel
{
public long VesselImoNumber { get; set; }
public string VesselName { get; set; }
public string VesselFlag { get; set; }
public string VesselCallSignNumber { get; set; }
public string VesselOperatorCarrierCode { get; set; }
public string VesselOperatorCarrierCodeListProvider { get; set; }
}
static readonly string myJson = #"{
""events"": [
{
""eventID"": ""6832920321"",
""eventType"": ""SHIPMENT"",
""eventDateTime"": ""2019-11-12T07:41:00+08:00"",
""eventCreatedDateTime"": ""2021-01-09T14:12:56Z"",
""eventClassifierCode"": ""ACT"",
""shipmentEventTypeCode"": ""DRFT"",
""documentTypeCode"": ""SHI"",
""documentID"": ""205284917""
},
{
""eventID"": ""6832920321"",
""eventType"": ""TRANSPORT"",
""eventDateTime"": ""2019-11-12T07:41:00+08:00"",
""eventCreatedDateTime"": ""2021-01-09T14:12:56Z"",
""eventClassifierCode"": ""ACT"",
""transportEventTypeCode"": ""ARRI"",
""documentReferences"": [
{
""documentReferenceType"": ""BKG"",
""documentReferenceValue"": ""ABC123123123""
},
{
""documentReferenceType"": ""TRD"",
""documentReferenceValue"": ""85943567-eedb-98d3-f4ed-aed697474ed4""
}
],
""transportCall"": {
""transportCallID"": ""123e4567-e89b-12d3-a456-426614174000"",
""carrierServiceCode"": ""FE1"",
""exportVoyageNumber"": ""2103S"",
""importVoyageNumber"": ""2103N"",
""transportCallSequenceNumber"": 2,
""UNLocationCode"": ""USNYC"",
""facilityCode"": ""ADT"",
""facilityCodeListProvider"": ""SMDG"",
""facilityTypeCode"": ""POTE"",
""otherFacility"": ""Balboa Port Terminal, Avenida Balboa Panama"",
""modeOfTransport"": ""VESSEL"",
""location"": {
""locationName"": ""Eiffel Tower"",
""latitude"": ""48.8585500"",
""longitude"": ""2.294492036"",
""UNLocationCode"": ""USNYC"",
""facilityCode"": ""ADT"",
""facilityCodeListProvider"": ""SMDG""
},
""vessel"": {
""vesselIMONumber"": 1801323,
""vesselName"": ""King of the Seas"",
""vesselFlag"": ""DE"",
""vesselCallSignNumber"": ""NCVV"",
""vesselOperatorCarrierCode"": ""MAEU"",
""vesselOperatorCarrierCodeListProvider"": ""NMFTA""
}
}
}
]
}";
EDIT: Result is something like:
I am working on an ASP.NET MVC application. Basically right now I'am trying to do the following: I created an API helper class that deserializes JSON data returned from Google Books API. In my Create.cshtml I only want to pass the ISBN of the book I am trying to add, however, as I discovered in debugger, ModelState.Is valid is false and therefore the new book does not get created. As far as I can see in the debugger, all the data gets pulled from the API correctly into the dictionary, however for some reason I can't store it my DB.
I know that there is probably a more elegant solution for this, but any kind of advice is more than welcome. Thank you for your time.
Here are the code files that might help:
APIHelper : deserializes JSON data and stores it in a Dictionary.
namespace APIHelper
{
public class IndustryIdentifier
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("identifier")]
public string Identifier { get; set; }
}
public class ReadingModes
{
[JsonProperty("text")]
public bool Text { get; set; }
[JsonProperty("image")]
public bool Image { get; set; }
}
public class ImageLinks
{
[JsonProperty("smallThumbnail")]
public string SmallThumbnail { get; set; }
[JsonProperty("thumbnail")]
public string Thumbnail { get; set; }
}
public class VolumeInfo
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("subtitle")]
public string Subtitle { get; set; }
[JsonProperty("authors")]
public IList<string> Authors { get; set; }
[JsonProperty("publisher")]
public string Publisher { get; set; }
[JsonProperty("publishedDate")]
public string PublishedDate { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("industryIdentifiers")]
public IList<IndustryIdentifier> IndustryIdentifiers { get; set; }
[JsonProperty("readingModes")]
public ReadingModes ReadingModes { get; set; }
[JsonProperty("pageCount")]
public int PageCount { get; set; }
[JsonProperty("printType")]
public string PrintType { get; set; }
[JsonProperty("categories")]
public IList<string> Categories { get; set; }
[JsonProperty("maturityRating")]
public string MaturityRating { get; set; }
[JsonProperty("allowAnonLogging")]
public bool AllowAnonLogging { get; set; }
[JsonProperty("contentVersion")]
public string ContentVersion { get; set; }
[JsonProperty("imageLinks")]
public ImageLinks ImageLinks { get; set; }
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("previewLink")]
public string PreviewLink { get; set; }
[JsonProperty("infoLink")]
public string InfoLink { get; set; }
[JsonProperty("canonicalVolumeLink")]
public string CanonicalVolumeLink { get; set; }
}
public class SaleInfo
{
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("saleability")]
public string Saleability { get; set; }
[JsonProperty("isEbook")]
public bool IsEbook { get; set; }
}
public class Epub
{
[JsonProperty("isAvailable")]
public bool IsAvailable { get; set; }
}
public class Pdf
{
[JsonProperty("isAvailable")]
public bool IsAvailable { get; set; }
}
public class AccessInfo
{
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("viewability")]
public string Viewability { get; set; }
[JsonProperty("embeddable")]
public bool Embeddable { get; set; }
[JsonProperty("publicDomain")]
public bool PublicDomain { get; set; }
[JsonProperty("textToSpeechPermission")]
public string TextToSpeechPermission { get; set; }
[JsonProperty("epub")]
public Epub Epub { get; set; }
[JsonProperty("pdf")]
public Pdf Pdf { get; set; }
[JsonProperty("webReaderLink")]
public string WebReaderLink { get; set; }
[JsonProperty("accessViewStatus")]
public string AccessViewStatus { get; set; }
[JsonProperty("quoteSharingAllowed")]
public bool QuoteSharingAllowed { get; set; }
}
public class SearchInfo
{
[JsonProperty("textSnippet")]
public string TextSnippet { get; set; }
}
public class Item
{
[JsonProperty("kind")]
public string Kind { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("etag")]
public string Etag { get; set; }
[JsonProperty("selfLink")]
public string SelfLink { get; set; }
[JsonProperty("volumeInfo")]
public VolumeInfo VolumeInfo { get; set; }
[JsonProperty("saleInfo")]
public SaleInfo SaleInfo { get; set; }
[JsonProperty("accessInfo")]
public AccessInfo AccessInfo { get; set; }
[JsonProperty("searchInfo")]
public SearchInfo SearchInfo { get; set; }
}
public class RootObject
{
[JsonProperty("kind")]
public string Kind { get; set; }
[JsonProperty("totalItems")]
public int TotalItems { get; set; }
[JsonProperty("items")]
public IList<Item> Items { get; set; }
}
public class APIHelper
{
public string Get(string uri)
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
public Dictionary<string, string> DictionaryReturnData(string isbn)
{
string path = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;
string json = Get(path);
Dictionary<string, string> responses = new Dictionary<string, string>();
var rootObject = JsonConvert.DeserializeObject<RootObject>(json);
foreach (var obj in rootObject.Items )
{
responses.Add("Title", obj.VolumeInfo.Title);
responses.Add("Description", obj.VolumeInfo.Description);
responses.Add("Image", obj.VolumeInfo.ImageLinks.Thumbnail);
responses.Add("Authors", string.Join(",", obj.VolumeInfo.Authors)); //list of strings
responses.Add("Genre", string.Join(",", obj.VolumeInfo.Categories)); //list of strings
responses.Add("Isbn", isbn);
responses.Add("Publisher", obj.VolumeInfo.Publisher);
responses.Add("PublishedDate", obj.VolumeInfo.PublishedDate);
responses.Add("PageCount", obj.VolumeInfo.PageCount.ToString());
}
return responses;
}
}
}
My Book class:
namespace BookstoreWeb.Models
{
public class Book
{
public int Id { get; set; }
[Required]
public string Isbn { get; set; }
[Required]
public string Title { get; set; }
public string Author { get; set; }
public double Price { get; set; }
[Required]
public string Description { get; set; }
public string Publisher { get; set; }
public string PublishedDate { get; set; }
public string PageCount { get; set; }
public string Thumbnail { get; set; }
public string Genre { get; set; }
}
}
Create Action
[HttpPost]
public IActionResult Create(Book model)
{
APIHelper.APIHelper helper = new APIHelper.APIHelper();
var responses = helper.DictionaryReturnData(model.Isbn);
model.Author = responses["Authors"];
model.Genre = responses["Genre"];
model.Isbn = responses["Isbn"];
model.Price = 10.00;
model.Title = responses["Title"];
model.Description = responses["Description"];
model.Publisher = responses["Publisher"];
model.PublishedDate = responses["PublishedDate"];
model.PageCount = responses["PageCount"];
model.Thumbnail = responses["Image"];
if (ModelState.IsValid) //check for validation
{
var newBook = new Book
{
Author = model.Author,
Genre = model.Genre,
Isbn = model.Isbn,
Price = model.Price,
Title = model.Title,
Description = model.Description,
Publisher = model.Publisher,
PublishedDate = model.PublishedDate,
PageCount = model.PageCount,
Thumbnail = model.Thumbnail,
};
newBook = _bookstoreData.Add(newBook);
_bookstoreData.Commit();
return RedirectToAction("Details", new {id = newBook.Id});
}
Removing the annotations [Required] from Book class seems to have solved the issue.
I am bit new to the serialization/deserialization of JSON's strings. I have tried to use Newtonsoft.Json. The thing is I got JSON string received from
url : http://epguides.frecar.no/show/gameofthrones/ and I would like to create and class objects from it. So later I could print it out...
I found out how to generate classes from your JSON string, by copying the string and Edit>Paste_Special>Paste_JSON_as_Classes so that should be alright.
Generated classes:
namespace TvSeries
{
public class Show
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__1
{
public Show show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class Show2
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__2
{
public Show2 show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class Show3
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__3
{
public Show3 show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class Show4
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__4
{
public Show4 show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class Show5
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__5
{
public Show5 show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class Show6
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__6
{
public Show6 show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class Show7
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__7
{
public Show7 show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class RootObject
{
public List<__invalid_type__1> __invalid_name__1 { get; set; }
public List<__invalid_type__2> __invalid_name__2 { get; set; }
public List<__invalid_type__3> __invalid_name__3 { get; set; }
public List<__invalid_type__4> __invalid_name__4 { get; set; }
public List<__invalid_type__5> __invalid_name__5 { get; set; }
public List<__invalid_type__6> __invalid_name__6 { get; set; }
public List<__invalid_type__7> __invalid_name__7 { get; set; }
}
}
Here is simple main class to print it out to the console:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
namespace TvSeries
{
class Program
{
static void Main(string[] args)
{
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("http://epguides.frecar.no/show/gameofthrones/");
//Console.WriteLine(json);
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
foreach (var item in obj.__invalid_name__1)
{
Console.WriteLine("Show: {0}, release date: {1}", item.show.title, item.release_date);
}
Console.ReadKey();
}
}
}
}
So the actual question is why is not deserializing or working properly, because the objects are still null? I am missing something important? I have also tried JavaScriptSerializer() but it doesn't fix my problem.
You use an attribute like this:
[JsonProperty("show")]
public Show2 Show2 { get; set; }
As user3791372 said, you should tidy up the generated classes. However these classes where generated because the response looks like this
{ "1":[{...}...], "2":[{...}...],...}. So you first need to get rid of "1", "2" and define your own types for clean code. the result will look like this
class Show
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
class Episode
{
public Show show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public DateTime release_date { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (WebClient wc = new WebClient())
{
//download json string
var json = wc.DownloadString("http://epguides.frecar.no/show/gameofthrones/");
//convert json to dynamic object
JObject obj = JObject.Parse(json);
//create an array that have as many elements as the children of obj => {"1", "2", "3", ...}
JArray[] results = new JArray[obj.Children().Count()];
//fill the array with the children of obj => results[6] = "[{"show": {"title": "Game of Thrones", "imdb_id": "tt0944947", "epguide_name": "gameofthrones"}, "title": "TBA", "number": 1, "season": 7, "release_date": "2017-06-25"}]"
for (int i = 0; i < results.Length; i++)
{
results[i] = (JArray)obj[(i + 1).ToString()];
}
//deserialize each item in results to List<Episode> if you checked the response it returns arrays of episodes
List<List<Episode>> seasons = new List<List<Episode>>(results.Length);
foreach (var item in results)
{
seasons.Add(JsonConvert.DeserializeObject<List<Episode>>(item.ToString()));
}
//output the result
foreach (var season in seasons)
{
foreach (var episod in season)
{
Console.WriteLine("Show: {0}, release date: {1}", episod.show.title, episod.release_date);
}
}
Console.ReadKey();
}
}
}
I'm trying to make an application that can show local TV guide trough JSON rest api C #, but has some problems with deserialization of my Json response.
i'm only intresest in the array NOW in my json call and i do not own the api service.
I get this error message:
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.DLL but was not handled in user code
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TDC_Play_TV_Mobil.superclass2+Now]' 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) 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 'now', line 1, position 7.
My function:
private HttpClient client;
public async Task<List<superclass2.Now>> GetComments()
{
client = new HttpClient();
var response = await client.GetAsync(new Uri("http://api.yousee.tv/rest/tvguide/nowandnext/"));
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(json);
var task = Task.Factory.StartNew(() => JsonConvert.DeserializeObject<List<superclass2.Now>>(json));
var value = await task;
// List<superclass2.Now> comments = Newtonsoft.Json.JsonConvert.DeserializeObject<List<superclass2.Now>>(await json);
System.Diagnostics.Debug.WriteLine("Comments er lavet");
return value;
}
else
{
throw new Exception("Errorhandling message");
}
}
My class file:
public class superclass2
{
public class Logos
{
public string small { get; set; }
public string large { get; set; }
public string small_seapp { get; set; }
public string large_seapp { get; set; }
public string extralarge { get; set; }
public string super { get; set; }
public string mega { get; set; }
public string netgem { get; set; }
public string svg { get; set; }
}
public class ChannelInfo
{
public string name { get; set; }
public string shortname { get; set; }
public string logo_image_prefix { get; set; }
public Logos logos { get; set; }
public int archivedays { get; set; }
public string channelcolor { get; set; }
}
public class FormattedDate
{
public string time_begin { get; set; }
public string time_end { get; set; }
public string date { get; set; }
}
public class ImagesSixteenbynine
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
}
public class ImagesFourbythree
{
public string large { get; set; }
public string small { get; set; }
}
public class ImagesSquare
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
}
public class Now
{
public int id { get; set; }
public int dvb_id { get; set; }
public int channel { get; set; }
public ChannelInfo channel_info { get; set; }
public string orgtitle { get; set; }
public string cast { get; set; }
public string directors { get; set; }
public string series_info { get; set; }
public int series_id { get; set; }
public string series_name { get; set; }
public bool allowseriesrecording { get; set; }
public int totalinarchive { get; set; }
public int popularity_score { get; set; }
public int totalupcoming { get; set; }
public int category { get; set; }
public int subcategory { get; set; }
public string category_string { get; set; }
public string subcategory_string { get; set; }
public int begin { get; set; }
public object actual_begin { get; set; }
public int end { get; set; }
public int actual_end { get; set; }
public int tvdate { get; set; }
public FormattedDate formatted_date { get; set; }
public string title { get; set; }
public string description { get; set; }
public bool archive { get; set; }
public bool scrubbingallowed { get; set; }
public int expiresfromarchive { get; set; }
public bool startover { get; set; }
public string imageprefix { get; set; }
public ImagesSixteenbynine images_sixteenbynine { get; set; }
public ImagesFourbythree images_fourbythree { get; set; }
public ImagesSquare images_square { get; set; }
public List<object> decorations { get; set; }
}
public class Logos2
{
public string small { get; set; }
public string large { get; set; }
public string small_seapp { get; set; }
public string large_seapp { get; set; }
public string extralarge { get; set; }
public string super { get; set; }
public string mega { get; set; }
public string netgem { get; set; }
public string svg { get; set; }
}
public class ChannelInfo2
{
public string name { get; set; }
public string shortname { get; set; }
public string logo_image_prefix { get; set; }
public Logos2 logos { get; set; }
public int archivedays { get; set; }
public string channelcolor { get; set; }
}
public class FormattedDate2
{
public string time_begin { get; set; }
public string time_end { get; set; }
public string date { get; set; }
}
public class ImagesSixteenbynine2
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
}
public class ImagesFourbythree2
{
public string large { get; set; }
public string small { get; set; }
}
public class ImagesSquare2
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
}
public class Next
{
public int id { get; set; }
public int dvb_id { get; set; }
public int channel { get; set; }
public ChannelInfo2 channel_info { get; set; }
public string orgtitle { get; set; }
public string cast { get; set; }
public string directors { get; set; }
public string series_info { get; set; }
public int series_id { get; set; }
public string series_name { get; set; }
public bool allowseriesrecording { get; set; }
public int totalinarchive { get; set; }
public int popularity_score { get; set; }
public int totalupcoming { get; set; }
public int category { get; set; }
public int subcategory { get; set; }
public string category_string { get; set; }
public string subcategory_string { get; set; }
public int begin { get; set; }
public int actual_begin { get; set; }
public int end { get; set; }
public int actual_end { get; set; }
public int tvdate { get; set; }
public FormattedDate2 formatted_date { get; set; }
public string title { get; set; }
public string description { get; set; }
public bool archive { get; set; }
public bool scrubbingallowed { get; set; }
public int expiresfromarchive { get; set; }
public bool startover { get; set; }
public string imageprefix { get; set; }
public ImagesSixteenbynine2 images_sixteenbynine { get; set; }
public ImagesFourbythree2 images_fourbythree { get; set; }
public ImagesSquare2 images_square { get; set; }
public List<object> decorations { get; set; }
}
public class RootObject
{
public List<Now> now { get; set; }
public List<Next> next { get; set; }
}
}
Your JSON isn't a List<superclass2.Now>, it's a superclass2.RootObject. So you need to do something like:
public async Task<List<superclass2.Now>> GetComments()
{
client = new HttpClient();
var response = await client.GetAsync(new Uri("http://api.yousee.tv/rest/tvguide/nowandnext/"));
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(json);
var task = Task.Factory.StartNew(() => JsonConvert.DeserializeObject<superclass2.RootObject>(json));
var value = await task;
System.Diagnostics.Debug.WriteLine("Comments er lavet");
return (value == null ? null : value.now);
}
else
{
throw new Exception("Errorhandling message");
}
}
Agree with Jon Skeet it would be nicer to eliminate the nesting of classes, purely for improved readability. If you need these classes to exist only in a specific scope, it is better to use nested namespaces. They aren't causing your bug, however.