我写的代码是:

import com.google.gson.Gson;
import com.google.gson.JsonObject;

 public class JsonFileCreation{
    public static JsonArray convertToJSON(ResultSet resultSet)
            throws Exception {
        JsonArray jsonArray = new JsonArray();
        while (resultSet.next()) {
            int total_columns = resultSet.getMetaData().getColumnCount();
            JsonObject obj = new JsonObject();
            for (int i = 0; i < total_columns; i++) {
                obj.put(resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase(), resultSet.getObject(i + 1));
            }
          jsonArray.put(obj);
        }
        return jsonArray;
    }
public static void main(String args[]) {
        Gson gson = new Gson();
        JsonArray jsonArr = new JsonArray();
        ....
        }


这在行中显示错误。它显示未为Json Object类型定义put(String,Object)。

jsonArray.put(obj);


我的ResultSet查询是-

sql = "SELECT * FROM EMPLOYEE";
ResultSet rs = stmt.executeQuery(sql);


该表如下所示:

Click here to view the table

我是初学者。请帮助我正确编写代码并在浏览器中获取json输出。

最佳答案

您得到的错误是:


没有为类型JsonObject定义put(String,Object)。


如果您查看JsonObjectGson Javadoc,则该消息是正确的。 JsonObject类没有put方法。

而是有一些add方法,您可能会想使用这些方法。

但是,没有add方法接受任何类型的对象并将其放入JSON。您将不得不自己处理各种不同类型的价值。您可能会获得null值,字符串,数字,日期以及其他可能的信息。

我建议创建一个新方法,如下所示,以处理向JSON对象obj添加单个值的情况。它将检查它知道的几种不同类型之间的给定值,并使用相关的JsonObject addaddProperty方法添加值:

    private static void addValueToJSON(JsonObject obj, String propertyName, Object value) throws Exception {
        if (value == null) {
            obj.add(propertyName, JsonNull.INSTANCE);
        } else if (value instanceof Number) {
            obj.addProperty(propertyName, (Number)value);
        } else if (value instanceof String) {
            obj.addProperty(propertyName, (String)value);
        } else if (value instanceof java.sql.Date) {
            // Not clear how you want dates to be represented in JSON.
            // Perhaps use SimpleDateFormat to convert them to a string?
            // I'll leave it up to you to finish this off.
        } else {
           // Some other type of value.  You can of course add handling
           // for extra types of values that you get, but it's worth
           // keeping this line at the bottom to ensure that if you do
           // get a value you are not expecting, you find out about it.
           throw new Exception("Unrecognised type of value: " + value.getClass().getName());
        }
    }


完成此操作后,您将通过替换该行来调用新方法

                obj.put(resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase(), resultSet.getObject(i + 1));




                addValueToJSON(obj, resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase(), resultSet.getObject(i + 1));


最后,您写道您的错误发生在网上

jsonArray.put(obj);


我不认为这是正确的,因为在此行上,您没有尝试在JsonObject上调用方法。但是,JsonArray类也没有put方法,因此此行上也有错误。这种情况下的错误更容易解决:像JsonObject类一样,JsonArray类也具有add方法,但是您可以使用采用JsonElement的方法,因为您要添加JsonObject到数组,并且JsonObject扩展JsonElement。这次的修复只是替换的一种情况

jsonArray.put(obj);




jsonArray.add(obj);

07-24 09:37
查看更多