Home > Blockchain >  APEX: Assigning a Map without a Key to a List
APEX: Assigning a Map without a Key to a List

Time:04-29

Sorry for the newbie question. Learning Apex here. Been working on an issue for several hours and can't seem to needle it out.

I have a JSON that I need converted to a List... the JSON is retrieved via an API. The code is pretty simple, it is only a couple of lines.

The JSON looks like this: {"id":1,"abbreviation":"ATL","city":"Atlanta","conference":"East","division":"Southeast","full_name":"Atlanta Hawks","name":"Hawks"}

And the code I am told to use to retrieve it looks like this:

Map<String, Object> resultsMap = (Map<String, Object>) JSON.deserializeUntyped(results.getBody());

Based on the JSON provided, there does not appear to be a MAP key being assigned, so I have no idea how to get it so that I may assign it to a List...

I've already tried assigning it directly to a List, but I didn't get much success there either.

I've tried this already:

List<Object> other = (List<Object>) results.get('');

I've also tried this: List<Object> other = (List<Object>) results.keySet()[0];

I'm sure it is something simple. Any help would be appreciated. Thanks

CodePudding user response:

Question can be disregarded. Not sure if there is a way to withdraw the question.

Question was based on the fact that previous APIs had been sent in the following format:

{"data": {"more stuff": "stuff"} }

And the map key was 'data' with a list. In this scenario, the whole API was a list and the keys to the map were set in place with the actual values instead.

CodePudding user response:

You cant convert the map to a list without an id. Alternatively why to convert it to List. Use the map itself. Below is a code example of how you can use it using your JSON response. For example, I want to insert this JSON response into the contact record, so I can map it using the MAP itself.:

@RestResource(urlMapping='/URIId/*') global class OwneriCRM {

@HttpPut
global static String UpdateOwnerinfo(){
    RestRequest req= RestContext.request;
    RestResponse res= RestContext.response;
    res.addHeader('Content-type','application/JSON');
    Map<String,Object> responseresult=new Map<String,Object>();
    Map<String,Object> results= (Map<String,Object>)JSON.deserializeUntyped(req.requestBody.toString());
     List<contact> insertList = new List<contact>();
    
    for (String key : results.keySet()){
    System.debug(results.get(key));
    contact c= new contact();
    c.ContactField__C = results.get(id);
    c.ContactField1__C = results.get(city);
    c.ContactField2__C = results.get(conference);
    c.ContactField3__C = results.get(division);
    c.ContactField3__C = results.get(full_name);
    c.ContactField3__C = results.get(name);
    insertList.add(c);
    
    }
    if(!insertList.Isempty()){
        update insertList;
    }
  • Related