Solucionado (ver solução)
Solucionado
(ver solução)
3
respostas

Lendo JSON file com API org.json

Estou tentando ler um arquivo JSON, no entanto ele lê um arquivo e aloca ' {} ', ou seja, um JSON vazio, no entanto o JSON possui valores. Segue o código:

import org.json.JSONObject;
import java.io.FileReader;
import java.io.IOException;

public static void main(String[] args) {
        JSONObject json;
        try {
            FileReader fileReader = new FileReader("exemplo.json");
            json = new JSONObject(fileReader);
            System.out.println(json.toString());
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Não foi possível ler o arquivo json");
        }
}

O JSON está na raiz do projeto, já tentei passar o path completo, no entanto não funciona da mesma forma.

3 respostas
solução!

Resolvi utilizando Stream e as novas features do Java 8

public static void main(String[] args) {
        JSONObject json = null;
        try {
            FileReader fileReader = new FileReader("exemplo.json");
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            List<String> collect = bufferedReader.lines().collect(Collectors.toList());
            StringBuilder jsonTemp = new StringBuilder();
            for (String s : collect) {
                jsonTemp.append(s);
            }
            json = new JSONObject(jsonTemp.toString());
            System.out.println(json.toString());
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Não foi possível ler o arquivo json");
        }
}
`

Oi amigo, problema resolvido então?

Abraço!

Sim! Tudo certo, valeu!

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software