如何将 JSON 映射到 java 模型类
Posted
技术标签:
【中文标题】如何将 JSON 映射到 java 模型类【英文标题】:how to map a JSON to a java model class 【发布时间】:2018-06-19 04:13:02 【问题描述】:我需要将JSON
obj 映射到一个类,并将它的数组映射到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"
]
]
]
【问题讨论】:
【参考方案1】:首先,您需要创建要在其中映射 JSON 的类。
还好有一个网站可以帮你搞定 here
其次,您可以使用googleGson库进行轻松映射
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。
【讨论】:
【参考方案2】:如果你使用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字符串转换为实体类。
【讨论】:
【参考方案3】:这是我在没有任何软件包的情况下如何做到的,这对我来说适用于小型用例:
我的模态类:
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"));
我还有另一个类可以从 assets 目录中获取 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
问候!
【讨论】:
以上是关于如何将 JSON 映射到 java 模型类的主要内容,如果未能解决你的问题,请参考以下文章
如何在没有 AttributeConverter 或 customUserType 的情况下使用 Hibernate 5.2.10 MySQL JSON 支持映射到 Java 实体类?