2

I'm having a weird problem that I can't seem to fix. Here's what's up:

I'm trying to read the contents of a JSON file so they can be processed and stored into a database. I was told I could only use minimal-json to do so.

The problem comes when i call Json.parse(), the process stops? It doesn't show any errors on the LogCat, just a warning. I have put a Log.d() to see if the JSON was being succesfully stored and it was, I'm just having problems with processing it.

Here's the class:

protected void onHandleIntent(Intent intent) {
    Log.d("JSONDownload", "entered onHandleIntent");
    String urlPath = intent.getStringExtra(URL);

    try {
        URL url = new URL(urlPath);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        Log.d("JSONDownload", "CONNECTED");

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream();
            Scanner scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\A");
            String jsonData = scanner.hasNext() ? scanner.next() : "";

            JsonObject json = Json.parse(jsonData).asObject();

            JsonArray imoveisArray = json.get("imoveis").asObject().get("imovel").asArray();
            JsonObject primeiroImovel = imoveisArray.get(0).asObject();
            String nomePrimeiroImovel = primeiroImovel.getString("descricao", "");
            Log.d("JSONDownload", "Name of first imovel: " + nomePrimeiroImovel);
            Toast.makeText(JsonDownload.this, nomePrimeiroImovel, Toast.LENGTH_SHORT).show();

            scanner.close();
            inputStream.close();
            result = Activity.RESULT_OK;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    publishResults(result);
}

It's a bit embarrassing that I need to ask this in Stack Overflow because it doesn't seem like a hard thing to correct but I just don't see what I can do. I appreciate all the help I can get.

1 Answers1

2

turns out, I had to play close attention to the encoding of the JSON. It was UTF-8 but with BOM. the BOM didn't allow for the parser to read it. after adapting the code, it ran smoothly. Here's what I did:

private static String removeBOM(String jsonString) {
    if (jsonString != null && jsonString.startsWith("\uFEFF")) {
        return jsonString.substring(1);
    }
    return jsonString;
}`

@Override
protected void onHandleIntent(Intent intent) {
    String urlPath = intent.getStringExtra(URL);
    HttpURLConnection con = null;
    InputStream is = null;

    try{
        //Inicialização da base de dados
        db = new DatabaseHelper(getApplicationContext());

        //Inicialização da conexão
        con = (HttpURLConnection) (new URL(urlPath)).openConnection();
        con.setRequestMethod("GET");
        con.setDoInput(true);
        con.connect();
        //eficiência em termos de leitura
        StringBuffer buffer = new StringBuffer();
        is = con.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String line = null;
        while((line = br.readLine()) != null){
            buffer.append(line + "\r\n");
        }
        is.close();
        con.disconnect();


        String jsonString = removeBOM(buffer.toString());

        // Print the JSON string for verification
        Log.d("JSONDownload", "JSON String: " + jsonString);

        // Parse the JSON
        JsonValue jsonValue = Json.parse(jsonString);

//from here on, you process the JSON however you'd like