如何将 JSON 映射到 java 模型 class

how to map a JSON to a java model class

我需要将 JSON obj 映射到 class 并将其数组映射到 Android 中的 ArrayList,并且它还应该包含所有子数据。 (也有嵌套的数组列表)我需要再次将更新的数据列表转换为 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"
              }
            ]
          }
        ]
      }
    ]
  }

如果您使用 JsonObject,您可以将 entity class 定义为:

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

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

首先,你需要在里面创建你要映射JSON的class。

幸运的是,有一个网站可以为您做这件事 here


其次,您可以使用google Gson库来轻松映射

1.添加 dependency.

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

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 的更多信息,请参阅此 tutorial

这是我在没有任何包的情况下的做法,这对我来说适用于小型用例:

我的模态 class:

package prog.com.quizapp.models;


import org.json.JSONException;
import org.json.JSONObject;

public class Question {
    private String question;
    private String correct_answer;
    private String answer_a;
    private String answer_b;
    private String answer_c;
    private String answer_d;

    public Question() {
    }

    public Question(String question, String answer_a, String answer_b, String answer_c, String answer_d, String correct_answer) {
        this.question = question;
        this.answer_a = answer_a;
        this.answer_b = answer_b;
        this.answer_c = answer_c;
        this.answer_d = answer_d;
        this.correct_answer = correct_answer;
    }

    public String getQuestion() {
        return question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    public String getCorrect_answer() {
        return correct_answer;
    }

    public void setCorrect_answer(String correct_answer) {
        this.correct_answer = correct_answer;
    }

    public String getAnswer_a() {
        return answer_a;
    }

    public void setAnswer_a(String answer_a) {
        this.answer_a = answer_a;
    }

    public String getAnswer_b() {
        return answer_b;
    }

    public void setAnswer_b(String answer_b) {
        this.answer_b = answer_b;
    }

    public String getAnswer_c() {
        return answer_c;
    }

    public void setAnswer_c(String answer_c) {
        this.answer_c = answer_c;
    }

    public String getAnswer_d() {
        return answer_d;
    }

    public void setAnswer_d(String answer_d) {
        this.answer_d = answer_d;
    }

    @Override
    public String toString() {
        return "Question{" +
                "question='" + question + '\'' +
                ", correct_answer='" + correct_answer + '\'' +
                ", answer_a='" + answer_a + '\'' +
                ", answer_b='" + answer_b + '\'' +
                ", answer_c='" + answer_c + '\'' +
                ", answer_d='" + answer_d + '\'' +
                '}';
    }

    public static Question fromJson(JSONObject obj) throws JSONException {
        return new Question(
                obj.getString("question"),
                obj.getString("answer_a"),
                obj.getString("answer_b"),
                obj.getString("answer_c"),
                obj.getString("answer_d"),
                obj.getString("correct_answer"));
    }
}

我还有另一个 class 从资产目录中获取 json 文件并将 JsonObject 映射到我的模型 class Question:

package prog.com.quizapp.utils;

import android.content.Context;
import android.util.Log;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;

import prog.com.quizapp.models.Question;

public class JsonSqlQueryMapper {
    private Context mContext;

    public JsonSqlQueryMapper(Context context) {
        this.mContext = context;
    }

    private static final String TAG = "JsonSqlQueryMapper";

    public JSONObject loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = mContext.getAssets().open("quiz_app.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }

        try {
            JSONObject quizObject = new JSONObject(json).getJSONObject("quiz");
            return quizObject;
        } catch (Exception e) {
            Log.d(TAG, "loadJSONFromAsset: " + e.getMessage());
            return null;
        }
    }

    public ArrayList<Question> generateInsertQueryForJsonObjects() {
        ArrayList<Question> questions = new ArrayList<>();
        JSONObject jsonObject = loadJSONFromAsset();
        try {
            Iterator<String> iter = jsonObject.keys();
            while (iter.hasNext()) {
                String key = iter.next();
                JSONObject value = jsonObject.getJSONObject(key);
                Question question = Question.fromJson(value.getJSONObject("question_two"));
                questions.add(question);
                Log.d(TAG, "generateInsertQueryForJsonObjects: " + question.getAnswer_a());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return questions;
    }
}

在我的 MainActivity -> onCreate:

  JsonSqlQueryMapper mapper = new JsonSqlQueryMapper(MainActivity.this);
  mapper.generateInsertQueryForJsonObjects();

检查是否一切如我所愿。如果你想检查 https://github.com/Blasanka/android_quiz_app/blob/sqlite_db_app/app/src/main/assets/quiz_app.json

,这里是 json 文件

此致!