如果我有一段类似于下面的代码:
conn.queryWithParams("select * from my_user where user_id = ?", params, { queryRes ->
if (queryRes.succeeded()) {
ResultSet rs = queryRes.result()
def objects = rs.getRows()
def user = new User()
def jsonObjectFromDB = objects.get(0)
user.userId = jsonObjectFromDB.getLong("user_id")
routingContext.response().setStatusCode(200).end(Json.encode(user))
} else {
// query failed
println "QUERY FAILED"
throw queryRes.cause()
}
})
而不是对用户对象的每个字段执行此操作:
user.userId = jsonObjectFromDB.getLong("user_id")
是否有更好的vert.x方法从数据库获取所有值并将它们放入相应的对象中?
答案 0 :(得分:3)
您应该能够像这样写一个POJO:
package some.package.or.other;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties
public class User {
private final String userId;
private final Integer someOtherValue;
@JsonCreator
public User(@JsonProperty("user_id") String userId,
@JsonProperty("some_other_value") Integer someOtherValue) {
this.userId = userId;
this.someOtherValue = someOtherValue;
}
public String getUserId() {
return userId;
}
public Integer getSomeOtherValue() {
return someOtherValue;
}
}
然后,您应该可以致电:
User user = io.vertx.core.json.Json.decodeValue(json, User.class);
杰克逊应该把它整理出来