0

I created a web service that returns a JSON formatted string in output but I have an error with the JSON parsing:

Unexpected token B in JSON at position 46

I tried to debug the program but I didn't find the error.

Here's the method that returns the JSON:

public String executeQueryTOJSON(String sql) // metodo utilizzato per eseguire i servizi di GET
{
    String error = "";

    StringBuilder json = new StringBuilder("[ ");
    if (_Connected) // controllo l'avvenuta connessione
    {
        try {
            stmt = _conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql); // executeQuery è un comando che permette di eseguire le query di
                                                   // selezione e restituisce le righe del risultato della query
            // System.out.println("query fatta");
            // a= rs.getString("accountname");

            java.sql.ResultSetMetaData rsmd = rs.getMetaData(); // oggetto rsmd con il comando getMetaData() viene
                                                                // utilizzato per scoprire le colonne dell'oggetto
                                                                // rs
            int cols = rsmd.getColumnCount(); // il comando getColumnCount() serve per calcolare il numero di
                                              // colonne dell'oggetto rsmd
            int count = 0; // variabile di appoggio per controllare se si trasferisce un valore nullo
            while (rs.next()) { // ciclo che si ripette in base alle righe di rs{
                // String foundType = rs.getString(1);
                // System.out.println(foundType);

                count++;
                json.append("{ ");
                // errore precedente -> "< cols" non faceva il giusto ciclo di parsing
                for (int i = 1; i <= cols; i++) // ciclo che si ripete per il numero oggetti situati nella tabella
                {
                    boolean check = false;
                    json.append("\"" + rs.getMetaData().getColumnLabel(i) + "\":");
                    switch (rsmd.getColumnType(i)) // switch per il controllo del valore da andar a prendere
                    {
                    case java.sql.Types.VARCHAR: {
                        String tmp = rs.getString(i);
                        // System.out.println(tmp);
                        if (tmp == null)// confronto per vedere se il valore è uguale a null
                        {
                            json.append("null");
                        } else
                            // modifica effettuata con .replace per sostiruire i caratteri errati
                            json.append("\"" + rs.getString(i).replace("\"", "'") + "\"");// replace usata per fare
                                                                                          // il giusto parsing
                    }
                        break;
                    case java.sql.Types.CHAR: {
                        // System.out.println(json.toString());
                        String tmp = rs.getString(i);
                        if (tmp == null)// confronto per vedere se il valore è uguale a null
                        {
                            json.append("null");
                        } else
                            json.append("\"" + rs.getString(i).replace("\"", "'") + "\"");
                    }
                        break;
                    case java.sql.Types.NULL: {
                        json.append("null");
                    }
                        break;
                    case java.sql.Types.DATE: {
                        try {
                            rs.getDate(i);
                            // json.append("\"" + rs.getDate(i) + "\"");
                            // check = true;
                        } catch (SQLException e) {

                        } finally {
                            json.append("\"\"");
                        }
                    }
                        break;
                    case java.sql.Types.INTEGER: {
                        json.append(rs.getInt(i));
                        check = true;
                    }
                        break;
                    default: {
                        if (check == false)
                            json.append(rs.getObject(i).toString());

                        // System.out.println(json);
                    }
                        break;
                    }
                    json.append(" , ");
                }
                json.setCharAt(json.length() - 2, '}');
                json.append(" , ");

                if (count == 0) {
                    json.append("\"risultato\":\"errore valore nullo\" }   ");
                }
            }
            json.setCharAt(json.length() - 2, ']');
            rs.close();
            stmt.close();
            _conn.close();// chiusura connessione con database

        } catch (SQLException e) {
            e.printStackTrace();
            return error = ("{ \"risultato\":\"errore query\" } ]");
        }
        // System.out.println(json.toString());
        return json.toString(); // output della Stringa JSON
    } else {
        return error = ("{ \"risultato\":\"errore connessione\" } ]");

    }
}

The JSON output looks like this:

[
    {
        "account_no": 77,
        "data": "",
        "quote_no": [B@7a9e5ed5,
        "codpag": "  56",
        "pag": "(  56) BONIFICO BANCARIO 120 GG DF",
        "codage": " 150",
        "agente": "( 150)  150 STRUTTURA PROVA"
    }
]

But it should return this:

[
    {
        "account_no": 77,
        "data": "",
        "quote_no": "PREV1400001",
        "codpag": "  56",
        "pag": "(  56) BONIFICO BANCARIO 120 GG DF",
        "codage": " 150",
        "agente": "( 150)  150 STRUTTURA PROVA"
    }
]
anothernode
  • 5,100
  • 13
  • 43
  • 62

3 Answers3

0

i think in this section:

 default:
    (check == false)
     json.append(rs.getObject(i).toString());
     //System.out.println(json);
    }

you are trying to turn object in string. unless you override the toString method to print values , it will always print [B@7a9e5ed5 . this code is the string value of object. you cannot turn object into string directly.

Shubham Kumar
  • 51
  • 2
  • 11
  • the error is here where you say.. how do i get the value? –  Feb 12 '19 at 09:54
  • look at the table column for that particular index. depends on what is the data type of column you are retrieving the data from. once you know the type of column then you can try to get value. – Shubham Kumar Feb 12 '19 at 09:57
0

You see, B@7a9e5ed5 is the address of the value which you want to show.

 json.append(rs.getObject(i).toString()); In this line, the to string method must be overriden for your type of object.

For example, If I have an object student of Class Student and if I have not overridden the toString() method. If I use student.toString(); It would print the address value where the object student is saved in the memory.

If for example I wanted to see the values of the student, I would have to override toString method in the class.

@Override
public String toString(){
   return this.getName() + " " + this.getClass();
}

The above is just an example, in your code, you need to know which type of object you are getting from the result set, and you need to override the method of toString in that class.

Hope this makes sense.

Farhan Qasim
  • 990
  • 5
  • 18
0

check flag is true only for integer .

For other type in the default block , you are directly converting object to String for non-character values you would need to override the toString method to have a accurate conversion .Make sure you override toString or provide String.valueOf with appropriate exception catching mechanisms

Neethi P
  • 9
  • 4