Reputation: 71
using (var client = new HttpClient())
{
HttpResponseMessage response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
var rootResult = JsonConvert.DeserializeObject<LastFMResponse_ArtistTracks>(result);
return rootResult;
}
else
{
return null;
}
}
The above string result returns the full json response that looks something like
{
"artisttracks": {
"track": [
{
"artist": {
"#text": "Flying Lotus",
"mbid": "fc7376fe-1a6f-4414-b4a7-83f50ed59c92"
},
"name": "Arkestry",
"streamable": "0",
"mbid": "5f2c6783-f876-4bbe-9577-d3498da6b0ab",
"album": {
"#text": "Cosmogramma",
"mbid": "7369257e-2346-4fe6-8810-c92c409d6671"
},
"url": "https://www.last.fm/music/Flying+Lotus/_/Arkestry",
"image": [
{
"#text": "https://lastfm-img2.akamaized.net/i/u/34s/50227cde795b4702c7b4d7ddcf0b85ff.png",
"size": "small"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/64s/50227cde795b4702c7b4d7ddcf0b85ff.png",
"size": "medium"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/174s/50227cde795b4702c7b4d7ddcf0b85ff.png",
"size": "large"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/300x300/50227cde795b4702c7b4d7ddcf0b85ff.png",
"size": "extralarge"
}
],
"date": {
"uts": "1530728536",
"#text": "04 Jul 2018, 18:22"
}
However the DeserializeObject method is not able to deserialize the string into the object that holds a text field instead of the #text one. The following is my class definition for the DeserializeObject destination.
public class LastFMResponse_ArtistTracks
{
public Artisttracks artisttracks { get; set; }
public class Artisttracks
{
public Track[] track { get; set; }
public Attr @attr { get; set; }
}
public class Attr
{
public string user { get; set; }
public string artist { get; set; }
public string page { get; set; }
public string perPage { get; set; }
public string totalPages { get; set; }
public string total { get; set; }
}
public class Track
{
public Artist artist { get; set; }
public string name { get; set; }
public string streamable { get; set; }
public string mbid { get; set; }
public Album album { get; set; }
public string url { get; set; }
public Image[] image { get; set; }
public Date date { get; set; }
}
public class Artist
{
public string text { get; set; }
public string mbid { get; set; }
}
public class Album
{
public string text { get; set; }
public string mbid { get; set; }
}
public class Date
{
public string uts { get; set; }
public string text { get; set; }
}
public class Image
{
public string text { get; set; }
public string size { get; set; }
}
}
Am I doing this the improper way or is there a way to get the text?
Upvotes: 1
Views: 125
Reputation: 46219
Because your JSON data name is #text
, Default JSON Convert can't bind with public string text { get; set; }
property
a simple way, you can try to add JsonProperty
Attribute on public string text { get; set; }
property.
[JsonProperty("#text")]
public string text { get; set; }
Upvotes: 1