【发布时间】:2021-03-12 05:14:06
【问题描述】:
我花了太多时间尝试完成这项工作,我是 Scala 新手。
基本上我向 API 发出请求并得到以下响应:
[
{
"id": "bde585ea-43ad-4e62-9f20-ea721193e0a5",
"clientId": "account",
"realm":"test-realm-uqrw"
"name": "${client_account}",
"rootUrl": "${authBaseUrl}",
"baseUrl": "/realms/test-realm-uqrw/account/",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"defaultRoles": [
"manage-account",
"view-profile"
],
"redirectUris": [
"/realms/test-realm-uqrw/account/*"
],
"webOrigins": [],
"protocol": "openid-connect",
"attributes": {},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": false,
"nodeReRegistrationTimeout": 0,
"defaultClientScopes": [
"web-origins",
"role_list",
],
"access": {
"view": true,
"configure": true,
"manage": true
}
},
{..another object of the same type, different values },
{..another object of the same type, different values }
]
我只需要从任何这些对象中提取"id" 字段(稍后我将通过realm 属性匹配)。有没有一种简单的方法可以将该 json 列表转换为 List[] 或 Map[String, Any]?我之所以说Any,是因为值的类型多种多样——布尔值、字符串、映射、列表。
我已经尝试了几种方法(内部工具)和 Jackson(错误:com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of scala.collection.immutable.List(no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information),我得到的最接近的是Tuples 给我的奇怪列表结果不正确(因为处理不正确)。
有什么简单的方法可以做到这一点?还是我注定要为此 API 响应创建一个自定义类?或者我可以直接遍历这个 JSON 文档(我只想从该数组中的 一个 对象中获取 一个 值)并提取该值吗?
【问题讨论】:
-
Jackson上面有很多Scala库,帮助Scala集成json用例:Circe、Json4s、Argonaut、LiftJson、Playjson