【问题标题】:Unexpected token B in JSON result from Java web service来自 Java Web 服务的 JSON 结果中的意外令牌 B
【发布时间】:2019-02-12 09:22:23
【问题描述】:

我创建了一个 Web 服务,它在输出中返回一个 JSON 格式的字符串,但我的 JSON 解析出错:

Unexpected token B in JSON at position 46

我尝试调试程序,但没有发现错误。

这是返回 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\" } ]");

    }
}

JSON 输出如下所示:

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

但它应该返回这个:

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

【问题讨论】:

    标签: java json


    【解决方案1】:

    我认为在这个部分:

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

    您正在尝试将对象转换为字符串。除非您覆盖 toString 方法以打印值,否则它将始终打印 [B@7a9e5ed5。此代码是对象的字符串值。 你不能直接把对象变成字符串。

    【讨论】:

    • 错误在你说的地方..我如何获得价值?
    • 查看该特定索引的表列。取决于您从中检索数据的列的数据类型。一旦你知道了列的类型,那么你就可以尝试获取价值。
    【解决方案2】:

    您看,B@7a9e5ed5 是您要显示的值的地址。

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

    例如,如果我有一个 Student 类的对象 student,并且我没有覆盖 toString() 方法。如果我使用student.toString();,它将打印对象学生在内存中保存的地址值。

    例如,如果我想查看学生的值,则必须重写类中的 toString 方法。

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

    以上只是一个例子,在你的代码中,你需要知道你从结果集中得到的是哪种类型的对象,并且你需要重写那个类中toString的方法。

    希望这是有道理的。

    【讨论】:

      【解决方案3】:

      检查标志仅对整数为真。

      对于默认块中的其他类型,您直接将对象转换为字符串以获得非字符值,您需要覆盖 toString 方法才能进行准确的转换。确保覆盖 toString 或提供带有适当异常的 String.valueOf捕捉机制

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-20
        • 2017-08-21
        • 1970-01-01
        • 2017-02-10
        • 1970-01-01
        • 1970-01-01
        • 2011-03-21
        • 2020-01-20
        相关资源
        最近更新 更多