如何将JSON映射到Java模型类

7

我需要将JSON对象映射到一个类,并将其数组映射到Android中的ArrayList,并且它应该包括所有子数据(包括嵌套的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"
              }
            ]
          }
        ]
      }
    ]
  }
3个回答

20

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

幸运的是,有一个网站可以为您做到这一点 这里


其次,您可以使用Google的 Gson 库进行简单的映射

1. 添加依赖项

        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的更多信息,请参见此教程


2
如果您使用JsonObject,您可以将您的实体类定义为以下内容:
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字符串为实体类。


2

以下是我在没有使用任何包的情况下所采用的方法,这对于小型应用场景来说非常实用:

我的模态框类:

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
祝好!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接