简体   繁体   中英

How to create json model class?

I'm trying to use this tutorial in my project to display listview with json array:

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

Here is a LocationModel.java and LocationList.java.

This is my 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
}

I have problem with write LocationModel for this json string.

How can i get elements from "active" and "completed"?

Thanks for help.

EDIT:

Thanks for good advie MByD ;) Unfortunately i still don't know how to use it.

In this code i get a "Data" elements from json.

I'm inside data object: {"data":{ . Next i want to get elements from "active"... how should i use your advice ? What next? Is it correct?

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

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

The classes structure should be something like this (according to the structure of your Json string) you should add getters and setters as I did not include them:

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;
}

To parse it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM