如何将JSON映射到java模型类

时间:2018-01-10 03:24:10

标签: java android json jsonserializer gson

我需要将JSON obj映射到一个类,将其数组映射到ArrayList中的Android,它也应该包含所有子数据。 (也有嵌套的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"
              }
            ]
          }
        ]
      }
    ]
  }

3 个答案:

答案 0 :(得分:6)

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

幸运的是,有一个网站可以为您 here

执行此操作

其次,您可以使用Google Gson库轻松进行映射

<强> 1。添加dependency

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

答案 1 :(得分:1)

如果您使用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字符串转换为实体类。

答案 2 :(得分:1)

这是我不使用任何程序包的方式,这对于小的用例来说对我来说是有用的:

我的模态班级:

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();

检查是否一切正常。如果您要检查https://github.com/Blasanka/android_quiz_app/blob/sqlite_db_app/app/src/main/assets/quiz_app.json

,则为json文件

致谢!