How to convert List into List

  • Here is my apex code"

    apex clas

    public class GetRestfulExampleSu{
    
    public string jsonStr {get;set;}
    public Pagereference getJSONFromREST() {
            Http h = new Http();
            HttpRequest req = new HttpRequest();
            req.setEndpoint('http://dz.co.rplug.renault.com/localsemiclair/BAWn'); 
            req.setHeader('Accept','application/JSON');
            req.setMethod('GET');
            HttpResponse res = h.send(req); 
            jsonStr= res.getBody();
    
            system.debug('jsonStr>>>>-->>>>>>'+jsonStr);
    
            jsonStr= res.getBody();
    
            Map<String,Object> rawObj = (Map<String,Object>) JSON.deserializeUntyped(jsonStr);
    
       Map<String,Object> responseObj = (Map<String,Object>)rawObj.get('localSemiClair');
       Map<String,Object> responseObjinside2 = (Map<String,Object>)responseObj.get('mapRepresentation'); 
       Map<String,Object> responseObjinside3 = (Map<String,Object>)responseObjinside2 .get('map');   
       List<Object> reqs = (List<Object>) responseObjinside3 .get('map');
       List<string> lsstr= new List<string> ();
    
       for(Object a:reqs){
         lsstr=(List<string>)a;  
       }
    
    
          return null;
     }
    
    }
    

    I want to convert "reqs" value into a list of string. It showing error.Please help me out.Thanks in advance!!

    instead of **lsstr=(List)a;** use **lsstr=(String)a;**

    what is the error you are getting?

    System.NullPointerException: Attempt to de-reference a null object

    instead of **lsstr=(List)a;** use **lsstr.add(String.valueOf(a));**

    @uma If this worked for you then please mark my answer as correct

  • Peeyush

    Peeyush Correct answer

    6 years ago

    Instead of this code:

    List<Object> reqs = (List<Object>) responseObjinside3 .get('map');
    List<string> lsstr= new List<string> ();
    
    for(Object a:reqs){
       lsstr=(List<string>)a;  
    }
    

    Use this code:

    List<Object> reqs = (List<Object>) responseObjinside3.values();
    List<string> lsstr= new List<string> ();
    
    for(Object a: reqs){
       lsstr.add(String.valueOf(a));
    }
    

    Yep works. But holy guacamole, for loops instead of lamba expressions. Apex ftw...

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used