M.S*_*idu 5 sql json postgresql-9.3 postgresql-9.5
我正在使用postgresql进行我的webapplication.我是这个Postgresql-json的新手.我只想以json结构的形式获取select查询结果.这是我的详细信息:
create table sample(id serial, info jsonb);
insert into sample("info") values('{"person": {"phone": 9804484234,"name":{"firstname":"Alice", "lastname":"bob"}, "empId": "E067", "age":25}');
Run Code Online (Sandbox Code Playgroud)
选择查询:
select "info"->'person'->>'lastname' from sample;
Run Code Online (Sandbox Code Playgroud)
结果:鲍勃
但我想得到上面的结果以及如下的json节点:
result: {"person":
{"name":
{"lastname":"bob"}
}
}
Run Code Online (Sandbox Code Playgroud)
任何机构都可以告诉我如何从数据库中获取我期望的结果结构.
将会变得更加简单:
A- 一个普通的 postgresSQL 数据库并将响应转换为 json。
A3。使用此代码将结果集转换为 json
public class SOF_36861985 {
public static JSONArray toJson(ResultSet res) throws Exception {
JSONArray array = new JSONArray();
while (res.next()) {
int size = res.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < size; i++) {
obj.put( res
.getMetaData()
.getColumnLabel(i + 1)
.toLowerCase(),
res.getObject(i + 1));
array.put(obj);
}
}
return array;
}
}
Run Code Online (Sandbox Code Playgroud)或者
B.使用mongoDB,即json原生数据库
解决方案 A 与解决方案 B 的比较
解决方案 A:sql + 不会强制您拥有一个新的数据库,您将继续使用 postgressql - 将从 ResultSet 转换为 Json - 将在 SQL 数据库中具有静态模式(没有像 nosql 中那样的动态模式)
解决方案 B:mongo - 更改数据库,这取决于生产......并且对基础设施有影响...... + 是 json 原生 DB + 对你来说可能是一个新的数据库,你将有一个学习时间来掌握它(将需要更多时间来设置、安装、开发...)
| 归档时间: |
|
| 查看次数: |
562 次 |
| 最近记录: |