如何显示来自Scala控制器类的正确json响应

如何显示来自Scala控制器类的正确json响应

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

问题描述

我正在尝试从Postgresql数据库(v9.5)表中获取json响应以显示在我的视图页面上,我尝试了以下操作,因为我的应用程序执行得很好,但是我没有获取/显示所需的正确json数据(因为它包含:Stream,slashes()和问号(?),例如Stream类型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响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:21