0

I get JSON response and I want this result {n=sometext} to be this result: sometext.

I have trying mid, replace, remove methods but I can't get a clean "sometext". My code is:

String inputText; 
for (Integer i = 0, j = 0; i < 3; i++) {
    if (inputText == null) {
     inputText = 'חי';
    } else if (inputText == 'חי') {
     inputText = 'תל';
    } else if (inputText == 'תל') {
       inputText = 'חי';
    } 

    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('http://www.israelpost.co.il/zip_data.nsf/CreateLocationsforAutocomplete?OpenAgent&callback&StartsWith=' + inputText  );
    request.setMethod('GET');
    HttpResponse response = http.send(request);
     System.debug(request);
    // If the request is successful, parse the JSON response.
    if (response.getStatusCode() == 200) {
     String myString=response.getBody().replace('\'','\\\'');
    //myString=response.getBody().replace('\\{n=}',' ');
     Integer myLength=myString.Length();
      //System.debug(myString.left(3));
      //System.debug(myLength);
      myString=myString.mid(1,myLength-4);
     //System.debug(myString);
      Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(myString);
      List<Object> animals = (List<Object>) results.get('locations');

      for (Object animal: animals) {
         System.debug(animal); 
      }
}
2
  • Could you try escapeSingleQuotes(stringToEscape) standard function to see if you can escape the special characters? What is the JSON you are getting? @Elia Jan 4 '17 at 7:51
  • the JSON that im getting is {n=sample text} and i want it to be only sample text
    – Elia
    Jan 4 '17 at 7:53
1

The response you are getting is the correct JSON format. You need not to replace or alter anything in the resoponse JSON string. Instead, when you deserialize the response, do the manipulations to remove 'n=' as shown below:

for (Object animal: animals) {
         System.debug('********************************'+String.valueOf(animal).replace('n=',''));
        }

Let me know if it helps!

4
  • my god this is working beautfully like magic thanks alot @Manjot Singh
    – Elia
    Jan 4 '17 at 9:52
  • @Elia is my answer working or @shailesh? Jan 4 '17 at 10:31
  • @shailesh answer is working
    – Elia
    Jan 4 '17 at 10:33
  • This is a hack FYI and not useful beyond this example. You should be deserializing the json into either an object or a class and work with that.
    – Eric
    Feb 13 '17 at 7:49
1

If you just want to get sometext from {n=sometext} then you can simply use replaceAll() method of a String. For example:

String yourString = '{n=sometext}';
String sometextString = yourString.replaceAll('\\{n=', '').replaceAll('}', '');
System.debug(sometextString);

this will replace all {n= and } with an empty strings

4
  • yes but the {n=sometext} stored as an object becuse of the jsonprasing
    – Elia
    Jan 4 '17 at 8:28
  • @Elia you can use response.getBody() to get the string and then call this method
    – Novarg
    Jan 4 '17 at 8:31
  • Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(myString); List<Object> animals = (List<Object>) results.get('locations'); for (Object animal: animals) { System.debug(animal); here is where i need to make animal to be animal whit the mid or remove the {n} from the response
    – Elia
    Jan 4 '17 at 8:47
  • see my last comment @Novarg
    – Elia
    Jan 4 '17 at 9:25
1

I suspect the way you are parsing the json response, I think you can adopt a simpler way to parse the json response by create a structured class for the response structure.

This approach requires you to have well defined Apex classes mapped to each of the structure/entity represented in the JSON string. If your apex class exactly resembles the JSON structure you can parse the whole JSON in just one line of code.

Lets take the classical example of Departments, Employees and Addresses i.e. Department has many employees and employee can have multiple addresses.

{
   "name":"Engineering",
   "code":"ENGR",
   "employees":[
      {
         "name":"James Bond",
         "mobile":"123-456-7892",
         "isMale":true,
         "age":29,
         "addresses":[
            {
               "street":"900 Concar Drive",
               "state":"CA",
               "postalCode":94402,
               "isPrimary":true,
               "country":"USA",
               "city":"San mateo"
            },
            {
               "street":"800 Bridgepointe",
               "state":"CA",
               "postalCode":29230,
               "isPrimary":false,
               "country":"USA",
               "city":"Foster City"
            }
         ]
      },
      {
         "name":"Brad Pitt",
         "mobile":"987-456-7892",
         "isMale":true,
         "age":35,
         "addresses":[
            {
               "street":"900 Rough Drive",
               "state":"CA",
               "postalCode":13245,
               "isPrimary":true,
               "country":"USA",
               "city":"SFO"
            }
         ]
      }
   ]
}

Object model in JSON

public with sharing class JsonParserTests {

    class Department {
        public String name;
        public String code;
        public Employee[] employees;        

        public Department(String n, String c) {
            this.name = n;
            this.code = c;
            this.employees = new List<Employee>();
        }        
    } 

    class Employee {
        public String name;
        public Integer age;
        public String mobile;
        public boolean isMale;
        public Address[] addresses;

        public Employee(String n, Integer a, String m, boolean im) {
            this.name = n;
            this.age = a;
            this.mobile = m;
            this.isMale = im;
            this.addresses = new List<Address>();
        }
    }

    class Address {
        public String street;
        public String city;
        public String state;
        public Integer postalCode;
        public String country;
        public boolean isPrimary;

        public Address( String street, String city, String state, Integer postalCode, String country, boolean isPrimary) {
            this.street = street;
            this.city = city;
            this.state = state;
            this.postalCode = postalCode;
            this.country = country;
            this.isPrimary = isPrimary;
        }
    }
} 

You can parse the json using single line -

Department d = (Department)JSON.deserialize(jsonToParse, JsonParserTests.Department.class);

Now you can replace the special characters. Let say if department's name contains special characters then you can simply apply

.replace()

method on it.

2
  • It does not need to match exactly. If can be missing field or have additional. But those you want to have cakes need to match
    – Eric
    Jan 4 '17 at 9:51
  • Missing will give you null value, you can put null checks. Jan 4 '17 at 10:44
-1

You can first split string at '='. You will get 'sample text}' then can use substring method to remove last word('}').

String newst = '{n=sample text}';

String splitedStr = newst.split('=')[1];

String requiredString = splitedStr.substring(0,splitedStr.length()-1));

2
  • It would be better if you can post some details or explanation, instead of just code :)
    – Raul
    Feb 12 '17 at 19:21
  • i have edited my question :) Feb 13 '17 at 7:00

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.