how to map a JSON to a java model class

只谈情不闲聊 提交于 2019-12-01 13:17:19
Bishoy Abd

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 {
          compile 'com.google.code.gson:gson:2.8.2'
         }  

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.

yu wang

If you use JsonObject, you can define your entity class as this:

public class Entity {
    String type;
    List<Crops> crops;
}

public class Crops {
    long crop_id;
    String crop_name;
    List<CropDetail> crop_details;
}

public class CropDetail {
    String created_id;
    List<Question> questions;
}

public class Question {
    int plants;
    String planted_by;
}

public void convert(String json){
    JsonObject jsonObject = new JsonObject(jsonstring);
    Entity entity = new Entity();
    entity.type = jsonObject.optString("type");
    entity.crops = new ArrayList<>();
    JsonArray arr = jsonObject.optJSONArray("crops");
    for (int i = 0; i < arr.length(); i++) {
        JSONObject crops = arr.optJSONObject(i);
        Crops cps = new Crops();
        cps.crop_id = crops.optLong("crop_id");
        cps.crop_name = crops.optString("crop_name");
        cps.crop_details = new ArrayList<>();
        JsonArray details = crops.optJsonArray("crop_details");
        // some other serialize codes
        ..........
     }
}

So you can nested to convert your json string to an entity class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!