猿问

使用改造使用复杂的 api 数据

{"data": 

  {

    "item1": {

            "name" : "Box"

            "price" : "50"


    },


    "item2": {

            "name" : "Bottle"

            "price" : "250"


    }, ..... 

    "item20": {

            "name" : "Pen"

            "price" : "100"

    }

}}

这是我的 API 结构。我无法为 20 个项目创建单独的 POJO 类,因为它效率不高。获取每件商品的名称和价格并将它们设置为回收商视图的最佳方法是什么?


慕雪6442864
浏览 183回答 3
3回答

米琪卡哇伊

您必须更改 JSON 的格式才能正确解析它。此外,您忘记在“名称”值后放置逗号。选项1:{&nbsp; &nbsp;"data":[&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"name":"Box",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"price":"50"&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"name":"Bottle",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"price":"250"&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"name":"Pen",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"price":"100"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;]}选项 2:{&nbsp; &nbsp;"data":{&nbsp; &nbsp; &nbsp; "item1":{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"name":"Box",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"price":"50"&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; "item2":{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"name":"Bottle",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"price":"250"&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; "item20":{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"name":"Pen",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"price":"100"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}}选项 1 是更好的选择,因为您将能够将“数据”表示为 android 中的数组或列表(例如ArrayList<Data>)。一般来说,我建议你使用像GSON这样的解析库

HUH函数

创建一个简单的类,然后按照图片中的说明进行操作单击“生成”选项后,您会看到 GsonFromat 单击,然后会提示一个框,如果您看不到 GsonFormat,则下载 GsonFormat 插件。这是您可以轻松创建 Pojo 类的最简单方法。将其放入框中并单击确定,它将自动为您创建类,您可以获取数据。{&nbsp; &nbsp;"data":[&nbsp; {&nbsp; &nbsp; &nbsp;"name":"Box",&nbsp; &nbsp; &nbsp;"price":"50"&nbsp; },&nbsp; {&nbsp; &nbsp; &nbsp;"name":"Bottle",&nbsp; &nbsp; &nbsp;"price":"250"&nbsp; },&nbsp; {&nbsp; &nbsp; &nbsp;"name":"Pen",&nbsp; &nbsp; &nbsp;"price":"100"&nbsp; }&nbsp; &nbsp;]&nbsp;}

慕桂英3389331

很简单,只需使用 GSON 创建一个带有 SerializableNames 的对象来保存 json。然后简单地创建一个你的 gson 兼容对象的 arrayList。其余的只是常见的适配器交互。我使用的 API 返回 json 对象的示例。它必须与您的 json 结构匹配。该示例在 Kotlin 中,但处理 json api 响应也是如此。
随时随地看视频慕课网APP

相关分类

Java
我要回答