web-dev-qa-db-ja.com

JSONをJavaモデルクラスにマップする方法

JSON objをクラスにマップし、その配列をArrayListAndroidにマップする必要があります。また、すべての子データも含まれている必要があります。 (ネストされた配列リストも使用)そして、更新されたデータリストを再び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"
              }
            ]
          }
        ]
      }
    ]
  }

これが私がパッケージなしでそれを行う方法です、これは小さなユースケースのために私のために仕事をします:

私のモーダルクラス:

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

そして、アセットディレクトリからjsonファイルを取得し、JsonObjectをモデルクラス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();

すべてが希望どおりに機能していることを確認します。確認したい場合は、jsonファイルを次に示します https://github.com/Blasanka/Android_quiz_app/blob/sqlite_db_app/app/src/main/assets/quiz_app.json

よろしく!

0
Blasanka