2

Hello guys i want to get Json array in fields,

I created 1 php file in a server and this php file to bring JSON data for the Product Informations, And after i wrote 1 apex code in Execute Anonymous and this code inside i want to get my fields but i couldnt reach,

As my following example

try 
{
        Http http = new Http();
        HttpRequest RequestProductList = new HttpRequest();
        RequestProductList.setEndPoint('388.221.34.12/ProductList.php');
        RequestProductList.setMethod('GET');
        RequestProductList.setTimeOut(120000);
        RequestProductList.setHeader('Content-Type','application/json');
        HttpResponse ResponseProductList = http.send(RequestProductList);

        if (ResponseProductList.getStatusCode() == 200)
        {

            Map<String,Object> results = (Map<String,Object>) JSON.deserializeUntyped(ResponseProductList.getBody());
            Map<String,Object> data = (Map<String,Object>) results.get('data');
            List<Object> Products = (List<Object>) data.get('productList');
            for(Object Prd: Products){
                system.debug(Products(Prd['AverageInventory'])); 
                ***ErrorMessage: Expression must be a list type: Object***
                   How can i get this AverageInventory field ? or others,

            }
        }
}
catch (exception ex){
    system.debug(ex);
}

1 Answer 1

2

Product again will be in the form of Map. So, you need to type-cast it to map and then get the field value:

for(Object Prd: Products){
       Map<String, Object> prdObject = (Map<String, Object>) Prd;
       System.debug('prdObject => '+prdObject);
       Integer AverageInventory = prdObject.containsKey('AverageInventory') : (Integer) prdObject.get('AverageInventory') : null; // OR Integer.valueOf(prdObject.get('AverageInventory'));
       System.debug('AverageInventory => '+AverageInventory);
       String MyStringField = prdObject.containsKey('MyStringField') : (String) prdObject.get('MyStringField') : null; // OR String.valueOf(prdObject.get('MyStringField'));
       System.debug('MyStringField => '+MyStringField);
   }
4
  • Firstly thanks for your answer i tried but now i get error message from to catch System.NullPointerException: Attempt to de-reference a null object Oct 25, 2019 at 8:30
  • That could be because you may not have the property you need. You can use containsKey for checking that. Also better to debug the prdObject and check for exact properties APIs. Oct 25, 2019 at 8:34
  • updated answer with code Oct 25, 2019 at 8:34
  • Yes ! its worked thanks for your answer :)))) and so thanks to you in this case i can check null fields :D Oct 25, 2019 at 8:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .