vertx-sql-client
vertx-sql-client copied to clipboard
Simple way convert row to JsonObject?
Dear Authors,
Is there has Simple way to convert JsonObject from row?
you mean a json object with row names as keys ?
not yet but there will be some mapping to JsonObject / DataObject in Vert.x 4 at least
yeah,The conversion method is a bit complicated now, some data types I have not done yet.
List<JsonObject> list = new ArrayList<>();
for (Row row : rows) {
int size = row.size();
JsonObject jsonObject = new JsonObject();
for (int i = 0; i < size; i++) {
String columnName = row.getColumnName(i);
Object value = row.getValue(i);
if(value != null){
if(value instanceof LocalDateTime){
jsonObject.put(columnName, ((LocalDateTime)value).atZone(
ZoneId.systemDefault()).toInstant());
} else {
jsonObject.put(columnName, row.getValue(i));
}
}
}
list.add(jsonObject);
}
return list;
In many cases, json serialization of the resultset/resultsets goes outside of the app server (e.g. to web client or service consumer) without any mangling.
IMHO, In these cases, it may be feasible JsonGenerator to be used for direct row serialization to the stream.
(Sorry if this is already aranged in vert.x, I not have learned the platform yet)
yeah,The conversion method is a bit complicated now, some data types I have not done yet. ...
This is presently what I am doing as well:
fun RowSet<Row>.toJson(): List<JsonObject> = asSequence().map { row ->
val json = JsonObject()
columnsNames().asSequence().forEach {
json.put(it, toPgType(row.getValue(it)))
}
json
}.toList()
private fun toPgType(value: Any?): Any? = when (value) {
is String -> value
is LocalDate -> value.format(DateTimeFormatter.ISO_DATE)
is LocalDateTime -> value.format(DateTimeFormatter.ISO_DATE_TIME)
else -> value
}
in Vert.x 4 we will try to improve this so one can store a date directly in JSON Object
yeah,The conversion method is a bit complicated now, some data types I have not done yet. ...
This is presently what I am doing as well:
fun RowSet<Row>.toJson(): List<JsonObject> = asSequence().map { row -> val json = JsonObject() columnsNames().asSequence().forEach { json.put(it, toPgType(row.getValue(it))) } json }.toList() private fun toPgType(value: Any?): Any? = when (value) { is String -> value is LocalDate -> value.format(DateTimeFormatter.ISO_DATE) is LocalDateTime -> value.format(DateTimeFormatter.ISO_DATE_TIME) else -> value }
If you use postgres TIMESTAMP WITH TIMEZONE
type, you also need this type mapping:
is OffsetDateTime -> value.format(DateTimeFormatter.ISO_DATE_TIME)
Outdated, tracked by #754 and solved in 4.0.0