【问题标题】:How to create json model class?如何创建 json 模型类?
【发布时间】:2011-08-08 14:09:22
【问题描述】:

我正在尝试在我的项目中使用本教程来显示带有 json 数组的列表视图:

https://bobbyprabowo.wordpress.com/2010/11/25/android-json-processing-using-gson-and-display-in-on-a-listview/

这是一个 LocationModel.java 和 LocationList.java。

这是我的 json:

{
   "data":{
      "totalQuests":"11",
      "active":[
         {
            "id":"1",
            "name":"TITLENAME",
            "description":"text",
            "text_when_complete":""
         },
         {
            "id":"2",
            "name":"TITELNAME2",
            "description":"Text2",
            "text_when_complete":""
         }
      ],
      "completed":[
         {
            "id":"3",
            "name":"TITLENAMECOMP",
            "description":"textCOMP",
            "text_when_complete":""
         }
      ]
   },
   "returnCode":0,
   "returnCodeDescription":null
}

我在为这个 json 字符串写入 LocationModel 时遇到问题。

如何从“活动”和“完成”中获取元素?

感谢您的帮助。

编辑:

感谢 MByD 的好建议 ;) 可惜我还是不知道怎么用。

在这段代码中,我从 json 中得到一个“数据”元素。

我在数据对象中:{"data":{。 接下来我想从“活动”中获取元素...... 我应该如何使用你的建议?接下来是什么?对吗?

private List<LocationModel> data;
public List<LocationModel> getQuests() {

    return data;
}
public void setLocationList(List<LocationModel> data) {
    this.data = data;
}

【问题讨论】:

    标签: java android json android-listview


    【解决方案1】:

    类结构应该是这样的(根据你的 Json 字符串的结构)你应该添加 getter 和 setter,因为我没有包括它们:

    class MyClass {
        Data data;
        Integer returnCode;
        Integer returnCodeDescription;
    }
    
    class Data {
        String totalRequests;
        Status[] active;
        Status[] completed;
    }
    
    class Status {
        String id;
        String name;
        String description;
        String textWhenCompleted;
    }
    

    解析它:

    MyClass class = new Gson().fromJson(yourJsonString, MyClass.class);
    

    【讨论】:

      【解决方案2】:

      您可以尝试使用类生成器工具。

      https://github.com/BrunoAlexandreMendesMartins/CleverModels

      【讨论】:

        猜你喜欢
        • 2016-01-21
        • 1970-01-01
        • 1970-01-01
        • 2023-01-31
        • 1970-01-01
        • 1970-01-01
        • 2021-11-05
        • 2020-01-10
        • 2020-04-27
        相关资源
        最近更新 更多