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.
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:
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[])));
I have created an API that I am now attempting to access through another application. Even though I am using Newtonsoft.JSON to both serialize and deserialize the JSON, I am encountering a conversion error, with the following InnerException:
{"Could not cast or convert from System.String to System.Collections.Generic.List`1[MidamAPI.Models.ManagerDTO]."}
The following is the snippet that throws the error (in RESTFactory):
public List<T> Execute<T>(String endPoint) where T : new() {
RestClient client = new RestClient(BASE_URL);
IRestRequest req = new RestRequest(endPoint);
req.AddHeader("Authorization", "Bearer " + this._token);
var response = client.Execute(req).Content;
List<T> responseData = JsonConvert.DeserializeObject<List<T>>(response);
return responseData;
}
which is called here:
{
RegisterViewModel vm = new RegisterViewModel();
RESTFactory factory = new RESTFactory((String)Session["bearer"]);
vm.availableManager = factory.Execute<ManagerDTO>("managers");
vm.availableProperties = factory.Execute<PropertyDTO>("locations");
vm.availableTrainers = factory.Execute<TrainerDTO>("trainers");
return View(vm);
}
The information is coming from the following API controller action (in a separate application):
[LocalFilter]
[RoutePrefix("managers")]
public class ManagersController : ApiController
{
UnitOfWork worker = new UnitOfWork();
[Route("")]
public string Get()
{
IEnumerable<ManagerDTO> dtoList = Mapper.Map<List<Manager>, List<ManagerDTO>>(worker.ManagerRepo.Get().ToList());
foreach (ManagerDTO dto in dtoList)
{
Manager manager = worker.ManagerRepo.GetByID(dto.ID);
dto.Stores = (Mapper.Map<IEnumerable<Property>, IEnumerable<PropertyDTO>>(manager.Properties)).ToList();
}
return JsonConvert.SerializeObject(dtoList);
}
The DTOs are the same in both applications:
{
public class ManagerDTO
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<PropertyDTO> Stores { get; set; }
}
public class PropertyDTO
{
public int ID;
public string ShortName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Lat { get; set; }
public string Long { get; set; }
public string GooglePlaceID { get; set; }
public string PropertyNumber { get; set; }
public int ManagerID { get; set; }
public int TrainerID { get; set; }
public string ManagerName { get; set; }
public string ManagerEmail { get; set; }
public string TrainerEmail { get; set; }
}
I tried using the json2csharp tool with the response, and everything seems fine to my eyes:
public class Store
{
public int ID { get; set; }
public string ShortName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Lat { get; set; }
public string Long { get; set; }
public string GooglePlaceID { get; set; }
public string PropertyNumber { get; set; }
public int ManagerID { get; set; }
public int TrainerID { get; set; }
public string ManagerName { get; set; }
public string ManagerEmail { get; set; }
public object TrainerEmail { get; set; }
}
public class RootObject
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<Store> Stores { get; set; }
}
Any advice would be appreciated.
EDIT:
The RegisterViewModel class
public class RegisterViewModel
{
public RegistrationDTO regModel { get; set; }
public List<ManagerDTO> availableManager { get; set; }
public List<PropertyDTO> availableProperties { get; set; }
public List<TrainerDTO> availableTrainers { get; set; }
}
Make your controller Get() return type
IHttpActionResult
and return
Ok(dtoList);
im trying to deserialize a Json that i get from a webservice Like so:
Uri urlJson = new Uri("http://optimizingconcepts.com/staging/cartuxa/system/json_request.php?lang=pt");
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(urlJson);
var jsonString = await response.Content.ReadAsStringAsync();
the Json i get is this:http://paste2.org/MpYJd8kk
I then do this to get the JsonObject:
JsonObject root = Windows.Data.Json.JsonValue.Parse(jsonString).GetObject();
What i want to know, is the correct way of saving each object from json to a list
so the objects from "home" would be in a List, the objects from "artigos" would go to a List and so on.
Using Json.Net, it can be done as follows
Uri urlJson = new Uri("http://optimizingconcepts.com/staging/cartuxa/system/json_request.php?lang=pt");
var client = new HttpClient();
var json = await client.GetStringAsync(urlJson);
var obj = JsonConvert.DeserializeObject<Cartuxa.RootObject>(json);
I used http://json2csharp.com/ to generate below classes.
public class Cartuxa
{
public class Home
{
public object id { get; set; }
public string menu { get; set; }
public string title { get; set; }
public string image { get; set; }
public string url { get; set; }
}
public class Artigo
{
public string menu { get; set; }
public string submenu { get; set; }
public string title { get; set; }
public string subtitle { get; set; }
public string description { get; set; }
public List<object> media { get; set; }
}
public class Year
{
public string year { get; set; }
public string title { get; set; }
public string description { get; set; }
public string file { get; set; }
public string url { get; set; }
}
public class Product
{
public string id { get; set; }
public string image { get; set; }
public string url { get; set; }
public List<Year> year { get; set; }
}
public class Vinho
{
public string id { get; set; }
public string menu { get; set; }
public string submenu { get; set; }
public string title { get; set; }
public List<Product> product { get; set; }
}
public class Year2
{
public string year { get; set; }
public string title { get; set; }
public string description { get; set; }
public string file { get; set; }
public string url { get; set; }
}
public class Product2
{
public string id { get; set; }
public string image { get; set; }
public string url { get; set; }
public List<Year2> year { get; set; }
}
public class Azeite
{
public string id { get; set; }
public string menu { get; set; }
public string submenu { get; set; }
public string title { get; set; }
public List<Product2> product { get; set; }
}
public class Agente
{
public string id { get; set; }
public string continent_id { get; set; }
public string country_id { get; set; }
public string title { get; set; }
public string description { get; set; }
}
public class Continente
{
public string id { get; set; }
public string title { get; set; }
}
public class Pais
{
public string id { get; set; }
public string continent_id { get; set; }
public string title { get; set; }
}
public class Contacto
{
public string id { get; set; }
public string menu_id { get; set; }
public string submenu_id { get; set; }
public string title { get; set; }
public string address { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
}
public class Premio
{
public string image { get; set; }
public string url { get; set; }
}
public class Noticia
{
public string id { get; set; }
public string menu { get; set; }
public string date_created { get; set; }
public string title { get; set; }
public string subtitle { get; set; }
public string description { get; set; }
public List<object> media { get; set; }
}
public class RootObject
{
public List<Home> home { get; set; }
public List<Artigo> artigos { get; set; }
public List<Vinho> vinhos { get; set; }
public List<Azeite> azeites { get; set; }
public List<Agente> agentes { get; set; }
public List<Continente> continentes { get; set; }
public List<Pais> paises { get; set; }
public List<Contacto> contactos { get; set; }
public List<Premio> premios { get; set; }
public List<Noticia> noticias { get; set; }
}
}