function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mark Z DeanMark Z Dean 

Apex Rest Callout Trailhead - List vs Map Question

I did this Trailhead challenge successfully but had a question. When I used List and casted the collection of maps into it, it kept giving me run time exception. 
public with sharing class AnimalLocator {
	public static  String  getAnimalById(Integer id) {
		String s;
		Http http = new Http();
		HttpRequest request = new HttpRequest();

		request.setEndpoint('' + id);
		HttpResponse response = http.send(request);
		if(response.getStatusCode() == 200){

			Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
			List<Object> animals = (List<Object>) results.get('animal');
			//System.debug('Animal is ' + animal.get(0));
			s = (String) animals.get(id);									}
	return s;

But when I converted it to use a map, it worked fine. I need some help to understand what could be the cause of this. Cheers!
Raj VakatiRaj Vakati
The Problem You can not typecast the Map into List... 

But try to case as objects ...

Mark Z DeanMark Z Dean
@Raj - I thought I was already casting in line 14. Am I not doing the right away?

@Alain - when I run the URI with the id appended, I get the following and its a singular:
{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"}}

When I run it without the id appended to the URL as in like,, I do see animals as plural. Shouldn't I be looking at the singular because that's what the requirement. I am getting more confused now so please clarify...
Mark Z DeanMark Z Dean
That's very interesting Alain...
Do you see any problems in the way I was casting in line 14 above, Raj raised that as problematic but I still don't know what its a problem?
Mark Z DeanMark Z Dean
Alain - sorry if I wasn't clear in my origianl question. I was actually trying to do the challenge and so the code is from that exercise and not from the Trailhead itself. 
Alain CabonAlain Cabon
Ok, the challenge asked for getAnimalNameById . It is not a project (just copy/paste) and you need to adapt the code indeed.

You were fully right so I deleted my useless posts. You already passed the challenge successfully.

The remote object (Animals) is still organized as a map even if you query only one item. That should be the most logical explanation but I will make some new tests.