0

I have created API URL for using autocomplete functionality as I give address in text box it display the related list of addresses. I need concatenate some address fields such as city, postcode, city code it display the next textbox. Please find below my JSON file and class. can you please suggest me what should I need to changes.

global class frenchaddress {

public String accName{get;set;}
public Id accId{get;set;}

public PageReference refresh(){
    return null;
}
  @RemoteAction
  global static List<String> restapi(string accName){

   string jsonStr;  
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://api-adresse.data.gouv.fr/search/?q=' + accName+ '');
        req.setHeader('Accept','application/JSON');
        req.setMethod('GET');
        HttpResponse res = h.send(req);
        system.debug('res.getBody()===>'+res.getBody().replace('\n', ''));
        List<String> calOut = new List<String>();

        jsonStr= res.getBody();

        JSONParser parser = JSON.createParser(jsonStr);

        while (parser.nextToken() != null) { 
        if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {

         String fieldName = parser.getText();

           if(fieldName == 'label'){
              parser.nextToken();
             calOut.add(parser.getText());               
           }        

             if(fieldName == 'context'){
               parser.nextToken();
             calOut.add(parser.getText());               
           }
              if(fieldName == 'city'){
              system.debug('city  ---->'+parser.getText());  
              parser.nextToken();
              calOut.add(parser.getText());               
           }    
                    }
                }   

          return calOut;

      }
    }


JSON File:

enter image description here

1

It sounds like your @RemoteAction should return multiple addresses where each address looks like "city, postcode, citycode". For that to work I would expect that the JSON returned would be an array of the objects you post in the question not a single object.

The easiest way to parse such a structure is to submit an example of it to JSON2Apex and use the code that is generated.

The return type of your @RemoteAction method remains List<String> but each item in the list is:

calOut.add(p.city + ', ' + p.postcode + ', ' + p.citycode);

assuming p is a reference to the properties field of one of the returned and parsed objects.

PS

The names here depend on what the JSON fields are called but the code would look something like this:

List<String> calOut = new List<String>();
JSON2Apex parsed = JSON2Apex.parse(res.getBody());
for (JSON2Apex.Feature f : parsed.feature) {
    JSON2Apex.Properties p = f.properties;
    calOut.add(p.city + ', ' + p.postcode + ', ' + p.citycode);
}
return calOut;
  • @ Keith I need to clarify more with you. I unable to send my whole class.. Where do I need to add properties exactly in @remote action . public class Properties { public String city; public String label; public String id; public String postcode; public String name; public String citycode; public String context; public Double score; public String type; } – Nikitha Jul 29 '15 at 8:00
  • @Nikitha You let JSON2Apex generate the code and then just use it JSON2Apex parsed = JSON2Apex.parse(res.getBody()). Google for blogs on the subject. I've added a "PS" with roughly how the code would look. – Keith C Jul 29 '15 at 8:18
0

Change the static method return type to string from the List<String> and

return the calOut list variable as

  @RemoteAction
  global static List<String> restapi(string accName)
  {

        string jsonStr;  
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://api-adresse.data.gouv.fr/search/?q=' + accName+ '');
        req.setHeader('Accept','application/JSON');
        req.setMethod('GET');
        HttpResponse res = h.send(req);
        system.debug('res.getBody()===>'+res.getBody().replace('\n', ''));
        List<String> calOut = new List<String>();

        List<String> finalcalOut = new List<String>();

        jsonStr= res.getBody();

        JSONParser parser = JSON.createParser(jsonStr);

        while (parser.nextToken() != null) 
        { 
            if (parser.getCurrentToken() == JSONToken.FIELD_NAME) 
            {

               String fieldName = parser.getText();

               if(fieldName == 'label')
               {
                  parser.nextToken();
                  calOut.add(parser.getText());               
               }        

               if(fieldName == 'context')
               {
                    parser.nextToken();
                    calOut.add(parser.getText());               
               }
               if(fieldName == 'city')
               {
                  system.debug('city  ---->'+parser.getText());  
                  parser.nextToken();
                  calOut.add(parser.getText());               
               }    
             }
             finalcalOut.add( String.join(calOut,', '); );
         }   
         return finalcalOut;
      }
    }

You would be getting something like

51, Marren, Champagne-Ardenne, Sezanne, 51120

  • @ Ashwani I replace return String.join('calOut',', '); for this return calOut but getting error. can you tell me what do I need to change anything. can you elaborate my code please. – Nikitha Jul 29 '15 at 7:13
  • @Nikitha did you change the return type of method as I written in answer? return should be String.join(calOut,', '); not String.join('calOut',', '); – Ashwani Jul 29 '15 at 7:15
  • 1
    This solution is working fine for a single property as mentioned above in json format...but I have to do this for many property...while using the above solution I get the answer like .........eg:51, Marren, Champagne-Ardenne, Sezanne, 51120,52,Mareny, Champagne, Sezanne23..all property values are getting in a single line...how to achieve each property in a single ?if yu need I wil send you the json !! – Nikitha Jul 29 '15 at 7:40
  • @Nikitha You can add String.join(calOut,', '); in a new List of type string and return that new List variable. In that case you will have to change return type again to List<String> – Ashwani Jul 29 '15 at 7:42
  • @Nikitha Updated the answer. – Ashwani Jul 29 '15 at 7:49
0

I prefer use a class as model to parse a JSON

I change your code to do it easier

global class frenchaddress {

public String accName{get;set;}
public Id accId{get;set;}

public PageReference refresh(){
    return null;
}
  @RemoteAction
  global static List<String> restapi(string accName){

   string jsonStr;  
    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint('http://api-adresse.data.gouv.fr/search/?q=' + accName+ '');
    req.setHeader('Accept','application/JSON');
    req.setMethod('GET');
    HttpResponse res = h.send(req);
    system.debug('res.getBody()===>'+res.getBody().replace('\n', ''));
    List<String> calOut = new List<String>();

    jsonStr= res.getBody();

    AddressResponse responseClass =(AddressResponse) JSON.deserialize(jsonStr, AddressResponse.class);
    if(responseClass.properties != null){
        return responseClass.properties.getFullAddress();
    } else {
        return null;
    }

  }
}


// CLASS MODEL RESPONSE CALL OUT APi-Adresse-DATA
public class AddressResponse{
    String type;
    AddressResponseProperties properties
}

public class AddressResponseProperties{
    public Strinc city;
    public String label;
    public String id;
    public String postcode;
    public String name;
    public String citycode;
    public String ontext;
    public Decimal score;
    public String type;

    public String[] getFullAddress(){
        return new String{this.city,this.citiycode,this.postcode};
    }
}
  • JSON2Apex will generate a starting point for that class for you. – Keith C Jul 29 '15 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.