how to map a JSON to a java model class

Thilina Dinith Fonseka picture Thilina Dinith Fonseka · Jan 10, 2018 · Viewed 18.8k times · Source

I need to map JSON obj to a class and its arrays to ArrayList in Android and it should have all the children data as well. (with nested arraylists too) and i need to convert updated data list again to jsonobject

my json string is

  {
    "type": "already_planted",
    "crops": [
      {
        "crop_id": 1,
        "crop_name": "apple",
        "crop_details": [
          {
            "created_id": "2017-01-17",
            "questions": [
              {
                "plants": "10"
              },
              {
                "planted_by": "A person"
              }
            ]
          },
          {
            "created_id": "2017-01-30",
            "questions": [
              {
                "plants": "15"
              },
              {
                "planted_by": "B person"
              }
            ]
          }
        ]
      },
      {
        "crop_id": 2,
        "crop_name": "Cashew",
        "crop_details": [
          {
            "created_id": "2017-01-17",
            "questions": [
              {
                "plants": "11"
              },
              {
                "planted_by": "c person"
              }
            ]
          }
        ]
      }
    ]
  }

Answer

Bishoy Abd picture Bishoy Abd · Jan 10, 2018

First of all, you need to create the class that you are going to map JSON inside.

Fortunately, there is a website that can do it for you here


secondly, you can use google Gson library for easy mapping

1. add the dependency.

        dependencies {
          implementation 'com.google.code.gson:gson:2.8.6'
         }  

2. from your object to JSON.

        MyData data =new MyData() ; //initialize the constructor 
        Gson gson = new Gson();  
        String Json = gson.toJson(data );  //see firstly above above
        //now you have the json string do whatever.

3. from JSON to object .

        String  jsonString =doSthToGetJson(); //http request 
        MyData data =new MyData() ; 
        Gson gson = new Gson();  
        data= gson.fromJson(jsonString,MyData.class); 
        //now you have Pojo do whatever

for more information about gson see this tutorial.