java 将结果集转换为 json 的最佳方法是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27593175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:05:04  来源:igfitidea点击:

what is the best way to convert resultset to json

javajsonjdbc

提问by yuria

I am getting the Resultsetfrom mySQLserver, and want to send it as JSONback to the client.. the server is writen in Java EE..

我正在ResultsetmySQL服务器获取,并希望将其发送JSON回客户端..服务器写在Java EE..

I have been looking up a lot for this.. but nothing simple.. is that elementary process really has to be that hard? or is there anything wrong in my understanding?

我一直在为此寻找很多东西..但没有什么简单的..那个基本过程真的必须那么难吗?还是我的理解有问题?

采纳答案by wassgren

Use Hymansonfor JSON-processing. If you convert your results to a POJO simply make the POJO Hymanson compatible(getters will be serialized automatically for instance or use @JsonProperty.

使用Hymanson进行 JSON 处理。如果您将结果转换为 POJO,只需使 POJO Hymanson 兼容(例如,getter 将自动序列化或使用@JsonProperty.

Example for converting a pojo to JSON:

将 pojo 转换为 JSON 的示例:

ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(somePojo);

If you do not convert your results to a POJO the JsonNodesubclass called ObjectNodecan be used.

如果您不将结果转换为 POJO,则可以使用所JsonNode调用的子类ObjectNode

Example:

例子:

public String convert(ResultSet rs) {
    ObjectNode node = new ObjectMapper().createObjectNode();
    node.put("fieldName", rs.getString("columnName"));
    return node.toString(); // this is proper JSON
}

However, the most common and clean approach is to return a POJO from your function (whether it is an EJB or a REST service or similar) and then let the framework convert it to JSON for you (typically the framework uses Hymanson). This means that your method simply returns some kind of model object that is Hymanson compatible.

然而,最常见和干净的方法是从您的函数(无论是 EJB 还是 REST 服务或类似服务)返回一个 POJO,然后让框架为您将其转换为 JSON(通常框架使用 Hymanson)。这意味着您的方法只是返回某种与Hymanson 兼容的模型对象。

回答by nagaraj v

https://gist.github.com/mreynolds/603526

https://gist.github.com/mreynolds/603526

public String convertResultSetToJson(ResultSet resultSet) throws SQLException {
    Joiner commaJoiner = Joiner.on(", \n");

    StringBuilder builder = new StringBuilder();
    builder.append("{ \"results\": [ ");

    List<String> results = new ArrayList<String>();

    while (resultSet.next()) {
        List<String> resultBits = new ArrayList<String>();

        ResultSetMetaData metaData = resultSet.getMetaData();
        for (int i = 1; i <= metaData.getColumnCount(); i++) {
            StringBuilder resultBit = new StringBuilder();
            String columnName = metaData.getColumnName(i);
            resultBit.append("\"").append(columnName).append("\": \"").append(resultSet.getString(i)).append("\"");
            resultBits.add(resultBit.toString());
        }

        results.add(" { " + commaJoiner.join(resultBits) + " } ");
    }

    builder.append(commaJoiner.join(results));
    builder.append("] }");
    return builder.toString();
}

回答by Baishali Ghosh

You may use JSONObjectprovided by org.json. Import org.json.JSONObjectinto your file. Then you can convert the resultset as follows:

您可以使用JSONObject由 提供org.json。导入org.json.JSONObject到您的文件中。然后您可以按如下方式转换结果集:

jsonObject = new JSONObject();
jsonObject.put(key,resultSet.getInt(resultSet.findColumn(columname)));
return jsonObject.toString();

So if you wanted to return a column with name NO_OF_DAYS having value 3 into a json object such as this {"days" : "3"}, you write the code as:

因此,如果您想将名称为 NO_OF_DAYS 且值为 3 的列返回到这样的 json 对象中{"days" : "3"},您可以将代码编写为:

jsonObject.put("days",resultSet.getInt(resultSet.findColumn("NO_OF_DAYS")));

回答by OhadR

@SuppressWarnings("unchecked")      //we use 3rd-party non-type-safe types...
public static String convertResultSetToJson(ResultSet resultSet) throws SQLException
{
    JSONArray json = new JSONArray();
    ResultSetMetaData metadata = resultSet.getMetaData();
    int numColumns = metadata.getColumnCount();

    while(resultSet.next())             //iterate rows
    {
        JSONObject obj = new JSONObject();      //extends HashMap
        for (int i = 1; i <= numColumns; ++i)           //iterate columns
        {
            String column_name = metadata.getColumnName(i);
            obj.put(column_name, resultSet.getObject(column_name));
        }
        json.add(obj);
    }
    return json.toJSONString();
}

source: https://github.com/OhadR/ohadr.common/blob/master/src/main/java/com/ohadr/common/utils/JsonUtils.java

来源:https: //github.com/OhadR/ohadr.common/blob/master/src/main/java/com/ohadr/common/utils/JsonUtils.java

you can use easily: JsonUtils.convertResultSetToJson(...)

您可以轻松使用: JsonUtils.convertResultSetToJson(...)

Grab the JAR from Maven Central,

从 Maven Central 获取 JAR,

<!-- https://mvnrepository.com/artifact/com.ohadr/ohadr.commons -->
<dependency>
    <groupId>com.ohadr</groupId>
    <artifactId>ohadr.commons</artifactId>
    <version>0.3</version>
</dependency>