如何从 Scala 控制器类显示正确的 json 响应? [英] How to show proper json response from Scala controller class?

查看:15
本文介绍了如何从 Scala 控制器类显示正确的 json 响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 Postgresql 数据库 (v9.5) 表中获取 json 响应以显示在我的视图页面上,我尝试了以下操作,因为我的应用程序运行良好,但我没有获取/显示我所需的正确 json数据(因为它包含:流、斜线()和问号(?),如流类型 json).请让我知道如何显示我想要的输出,如下所示?我的输出:

I am trying to get json response from Postgresql database(v9.5) table to display on my view page, I have tried the following, as my application is executing fine, but I am not getting/displaying my required proper json data(as it is containing: Stream, slashes() and question mark(?), like Stream type json). Please let me know that how to show my desired output like below ? my output:

Stream("[{"_testid":{"testid0":"testnumber"},"testtitle":"TestTitle"}]", ?)

但我想要的输出:

[{"_testid":{"testid0":"testnumber"},"testtitle":"TestTitle"}]

控制器:

class Test extends Controller {
    def getTest = Action { 
    var sql: SqlQuery = SQL("select name::TEXT from test");
    def values: String =  DB.withConnection { implicit connection => 
    sql().map(row => row[String]("name")).toString
    }
    Ok(values)
    }

表格:

create table test(
    id serial primary key,
    name json not null);

推荐答案

如文档所示,Anorm 自带 列解析器 用于 JDBC 标准类型.

As indicated in the documentation, Anorm comes with column parsers for the JDBC standart types.

PostgreSQL JSON 类型不是其中之一.这是供应商特定的类型.

PostgreSQL JSON type is not one of those. It's a vendor specific type.

您可以在语句中处理这种特定的转换,通过将 SQL 列转换为 TEXT 之前通过 JDBC(如普通的 JDBC String 那样).

You can deal with this specific conversion in the statement, by casting the SQL column to TEXT before to go through the JDBC (as plain JDBC String so).

SELECT json_col::TEXT FROM test

您可以实现自定义Column[JsValue](参见文档),将特定于 PostgreSQL JDBC 驱动程序的 PGObject 转换为 Play JsValue代码>.

You can implement a custom Column[JsValue] (see documentation), that convert the PGObject specific to the PostgreSQL JDBC driver into a Play JsValue.

您可以将列映射为 anorm.Object (SqlParser.get[anorm.Object]("col")),并在您的应用.

You can map the column as anorm.Object (SqlParser.get[anorm.Object]("col")), and deal with the opaque value in your application.

这篇关于如何从 Scala 控制器类显示正确的 json 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆