-1

I want to iterate through my JSON response in viewmodel MVC so I am trying to incorporate IEnumerable for this:

ArtistInfoResponse IMusicRepository.GetArtistResponse(string artistName)
{
    artistName = (char)34 + artistName + (char)34;
    RestClient client = new RestClient($"https://api.deezer.com/search?q=artist:{artistName}");

    RestRequest request = new RestRequest(Method.GET);
    IRestResponse response = client.Execute(request);

    if (response.IsSuccessful)
    {
        // Deserialize the string content into JToken object
        var content = JsonConvert.DeserializeObject<JToken>(response.Content);

        // Deserialize the JToken object into our ArtistInfoResponse Class
        return content.ToObject<ArtistInfoResponse>();
    }

    return null;
}

And I get this response:

From this Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'MyMusicApp.Models.ArtistInfoResponse' 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<T>) 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 'data'.'

Here is my class:

public class ArtistInfoResponse : IEnumerable
{
    public SongInfo[] Data { get; set; }
    public int Total { get; set; }
    public string Next { get; set; }

    public IEnumerator GetEnumerator()
    {
        throw new NotImplementedException();
    }
}
taraloca
  • 9,077
  • 9
  • 44
  • 77
  • 1
    What does your JSON string contain? Seems like a very similar problem to what I had earlier today. Solved it with this https://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n – Austin G Mar 02 '21 at 05:45
  • You need to apply the `JsonObjectAttribute` to your type. The default serializer will assume any `IEnumerable` is to be serialized as an array. – Jeff Mercado Mar 02 '21 at 06:09
  • Be able to enter part of Json data – Meysam Asadi Mar 02 '21 at 07:51
  • I am able to get the JSON deserialized into my class, it's then displaying the information in my viewmodel and iterating over the JSON response to do so. I thought I had to make it IEnumerable. – taraloca Mar 02 '21 at 13:13

1 Answers1

0

The response itself is an object and not an array. You should not implement IEnumerable for your ArtistInfoResponse class. The response only contains an array for data wich you have implemented correctly as SongInfo[].

EDIT: Here ist an example request for anyone who comes here: https://api.deezer.com/search?q=artist:dire%20straits

Sebastian
  • 1,569
  • 1
  • 17
  • 20