如何将JSON映射到java模型类

我需要将json obj映射到一个类,并将其数组映射到android中的arraylist,它也应该包含所有子数据。 (也有嵌套的arraylists)我需要再次将更新的数据列表转换为jsonobject

我的json字符串是

{ "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" } ] } ] } ] } 

首先,您需要创建要在其中映射JSON的类。

幸运的是,有一个网站可以在这里为你做


其次,您可以使用谷歌Gson库轻松映射

1.添加依赖项 。

  dependencies { compile 'com.google.code.gson:gson:2.8.2' } 

2.从你的对象到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.从JSON到对象。

  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 

有关gson的更多信息,请参阅本教程 。

如果使用JsonObject,则可以将实体类定义为:

 public class Entity { String type; List crops; } public class Crops { long crop_id; String crop_name; List crop_details; } public class CropDetail { String created_id; List 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 .......... } } 

因此,您可以嵌套将json字符串转换为实体类。