ReignOfComputer
ReignOfComputer

Reputation: 757

Get specific data from first JsonArray

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();

Upvotes: 1

Views: 45

Answers (1)

SpruceMoose
SpruceMoose

Reputation: 10320

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;

Upvotes: 2

Related Questions