JSON data return without spacing

Asked

Viewed 65 times

0

I have a class that has a single method to make a request for data that are in JSON format and return a single "fantasy" field that in my case is stored in the Company name variable.

This class works perfectly, the only problem is that my result is missing the gaps between the company name. Below is an example and the code.

Any help will be welcome.

Example:

What I want after the consultation: New Supermarket

What I’m getting after the consultation: Supermarket

Code:

public class NomeFantasia {

    public String nomeEmpresa;

    public String nomeFantasiaMetodo(String cnpj){

        StringBuilder resposta = new StringBuilder();

        try {

            URL url = new URL("https://www.receitaws.com.br/v1/cnpj/" + cnpj);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);
            connection.setConnectTimeout(5000);
            connection.connect();

            Scanner scanner = new Scanner(url.openStream());
            while (scanner.hasNext()) {
                resposta.append(scanner.next());
            }

            JSONObject my_obj = new JSONObject(String.valueOf(resposta));
            nomeEmpresa = my_obj.getString("fantasia");

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }


        return nomeEmpresa;


    }
}
  • Hello Lucas, please leave the first letter of the sentence in uppercase.

1 answer

1


I was able to solve it, just change the answer.append(scanner.next()); by reply.append(scanner.nextLine());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.