1

I'm trying to get data from an API that returns data in the format:

[{
    "song": {
        "id": 12345,
        "track": "TRACK A",
        "artist": "ARTIST A"
    },
    "playedtime": "2018-02-14T09:07:15.976"
}, {
    "song": {
        "id": 54321,
        "track": "TRACK B",
        "artist": "ARTIST B"
    },
    "playedtime": "2018-02-14T09:03:29.355"
}]

I need to get only the first track and artist entry, which in the above example is "TRACK A" and "ARTIST A".

What I've done so far which is probably really wrong is:

string response = await client.GetStringAsync(uri);
JArray parser = JArray.Parse(response);
rootTrack = JObject.Parse(parser.First.ToString())["track"].ToString();
rootArtist = JObject.Parse(parser.First.ToString())["artist"].ToString();
2
  • the json isnt valid. Commented Feb 14, 2018 at 9:11
  • @MichaelRandall my bad, edited. Commented Feb 14, 2018 at 9:14

1 Answer 1

2

I recommend creating a c# representation of your data as follows:

public class Song
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("track")]
    public string Track { get; set; }

    [JsonProperty("artist")]
    public string Artist { get; set; }
}

public class PlayListItem
{
    [JsonProperty("song")]
    public Song Song { get; set; }

    [JsonProperty("playedtime")]
    public DateTime PlayedTime { get; set; }
}

You can then use JSON.net to deserialize your JSON data and access the required properties as follows:

List<PlayListItem> playList = JsonConvert.DeserializeObject<List<PlayListItem>>(response);

PlayListItem firstItem = playList.First();
string track = firstItem.Song.Track;
string artist = firstItem.Song.Artist;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.