【问题标题】:Is there an easy way to flatten a json:api response on Android?有没有一种简单的方法可以在 Android 上展平 json:api 响应?
【发布时间】:2020-08-15 13:14:59
【问题描述】:

我正在尝试将以下响应展平,而不必将其解析为一个类。这样做的原因是服务器可以随时添加或删除字段,因此它需要是动态的。我们还有另一个服务,它返回查找路径,我们用它来从扁平响应中获取数据——比如“$.detail.att_one”有一个 iOS 库可以做我正在寻找的确切事情,但就我而言在 Android 上找不到类似的东西:https://github.com/infinum/Japx

{
"data": [
    {
        "type": "items",
        "id": "14",
        "attributes": {
            "item_type": "shape_circle",
            "code": null,
            "size": "70"
        },
        "relationships": {
            "detail": {
                "data": {
                    "type": "circle",
                    "id": "90"
                }
            },
            "metadata": {
                "data": "metadata"
            }
        },
        "links": {
            "self": "http://url/item/14"
        }
    }
],
"included": [
    {
        "type": "circle",
        "id": "90",
        "attributes": {
            "att_one": 4,
            "att_two": "11111111111",
            "att_three": "Bob"
        }
    }
]}

我正在寻找的结果:

{
"data": [
    {
        "id": "14",
        "type": "items",
        "item_type": "shape_circle",
        "code": null,
        "size": "70",
        "metadata": {
            "data": "metadata"
        },
        "detail": {
            "type": "circle",
            "id": "90",
            "att_one": 4,
            "att_two": "11111111111",
            "att_three": "Bob"
        },
        "links": {
            "self": "http://url/item/14"
        }
    }
]}

【问题讨论】:

  • 你知道 OkHttp 或 Retrofit 库是如何工作的吗?看看它们以及它们如何使用 Gson 或 Moshi 进行序列化。
  • 是的,我已经在使用 Retrofit 和 Moshi 从服务器获取响应。我可以使用与响应中的字段相对应的@Json 字段创建一个类,但我想避免这种情况,因为我希望能够传递原始 json,但只有在它被展平为像上面的结果
  • 所以你不想序列化响应?使用 JSON 库接收 JSON 对象,然后将其传递。
  • 是的,这就是我想要做的,我的问题是扁平化 json 以将包含的内容合并为我正在寻找的格式(我的问题中的最后一个 json 代码块),然后还有能够将其取消展平,以便我可以将其发送回服务器

标签: java android json kotlin json-api


【解决方案1】:

有一个很好的 JSONAPI 库可以做这件事,但你必须为它定义资源类。

查看jasminb/jsonapi-converter

它递归地展平所有包含的关系并处理继承。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-07
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多