gpt4 book ai didi

java - 在Java中将带有数组的json字符串转换为平面键的最佳方法

转载 作者:行者123 更新时间:2023-11-30 08:07:58 28 4
gpt4 key购买 nike

我有一个具有以下结构的 JSON 文件。

    [
{
"type":[
"blog",
"article",
"pressrelease"
],
"states":[
"scheduled",
"published"
],
"roles":[
"editor",
"admin"
],
"actions":[
"review",
"delete"
]
},
{
"type":[
"blog",
"article",
"pressrelease"
],
"states":[
"draft",
"review"
],
"roles":[
"editor",
"admin"
],
"actions":[
"submit",
"delete"
]
},
{
"type":[
"blog",
"article"
],
"states":[
"draft",
"review"
],
"roles":[
"author"
],
"actions":[
"submit"
]
},
{
"type":[
"pressrelease"
],
"states":[
"draft",
"review"
],
"roles":[
"pr",
"prm"
],
"actions":[
"submit"
]
},
{
"type":[
"pressrelease"
],
"states":[
"scheduled",
"published"
],
"roles":[
"prm"
],
"actions":[
"review",
"delete"
]
}
]

我需要编写一个方法,对于给定的场景,该方法将根据上面的 json 返回操作。

getActions(type, state, role){
}

我计划使用 GSON 将 json 转换为 Action 类对象列表,然后通过使用很少的 for 循环处理 json 来构建一个静态映射,其中键为 type.state.role,值作为操作列表。我的 map 将有

"blog.scheduled.editor" : ["review", "delete"]
"blog.scheduled.admin" : ["review", "delete"]
"blog.published.editor" : ["review", "delete"]

......

"pressrelease.draft.pr" : ["submit"]

因此,在 getActionas 方法中,我可以通过从输入值创建键来轻松返回操作。

我不确定这是否是正确的实现,或者是否有实用程序可以完成这项工作。

最佳答案

您的方向是正确的,但我建议使用树而不是 map ,因为它是此类数据的更自然的表示。

像这样构建你的树:

* [Root]
|___ blog
| |___ published
| | |___ editor
| | | |___ review
| | | |___ delete
| | |
| | |___ admin
| | | |___ review
| | | |___ delete
| | |
| |
| |___ scheduled
| | |___ admin
| | | |___ delete
| | | |___ review
| | |
| | |___ editor
| | | |___ review
| | | |___ delete
| | |
| |
|
|___ pressrelease
| |___ scheduled
| | |___ admin
| | | |___ delete
| | | |___ review
(I spend far too much time on that ASCII tree ...)

然后,您可以从一个节点“向下”走三个节点并检查子节点。

这样,您还可以检查博客条目上可能存在哪些状态,并且(如果您以不同的方式重新排序或创建树)您可以检查管理员可以对文章执行哪些操作。

关于java - 在Java中将带有数组的json字符串转换为平面键的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30819078/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com