How to show proper json response from Scala controller class?

那年仲夏 提交于 2019-12-20 06:58:11

问题


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\"}]", ?)

but my desired output:

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

contorller:

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)
    }

table:

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

回答1:


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

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

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

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

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



来源:https://stackoverflow.com/questions/35619921/how-to-show-proper-json-response-from-scala-controller-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!