来自 Java Web 服务的 JSON 结果中的意外令牌 B

我创建了一个 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


 

绝地无双
浏览 126回答 3
3回答

侃侃尔雅

我认为在本节中:&nbsp;default:&nbsp; &nbsp; (check == false)&nbsp; &nbsp; &nbsp;json.append(rs.getObject(i).toString());&nbsp; &nbsp; &nbsp;//System.out.println(json);&nbsp; &nbsp; }您正在尝试将对象转换为字符串。除非您覆盖 toString 方法以打印值,否则它将始终打印 [B@7a9e5ed5。此代码是对象的字符串值。你不能直接把对象变成字符串。

米琪卡哇伊

你看,B@7a9e5ed5是你要显示的值的地址。&nbsp;json.append(rs.getObject(i).toString()); In this line, the to string method must be overriden for your type of object.例如,如果我有一个studentClass Student的对象并且我没有覆盖该toString()方法。如果我使用student.toString();它将打印对象学生保存在内存中的地址值。例如,如果我想查看学生的值,我将不得不重写类中的 toString 方法。@Overridepublic String toString(){&nbsp; &nbsp;return this.getName() + " " + this.getClass();}上面只是一个例子,在你的代码中,你需要知道你从结果集中得到了哪种类型的对象,并且你需要重写那个类中 toString 的方法。希望这是有道理的。

米脂

检查标志仅对整数为真。对于默认块中的其他类型,您直接将对象转换为 String 以获得非字符值,您需要覆盖 toString 方法才能进行准确的转换。确保覆盖 toString 或提供具有适当异常捕获机制的 String.valueOf
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java