Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to map a JSON to a java model class

I need to map JSON obj to a class and its arrays to ArrayList in Android and it should have all the children data as well. (with nested arraylists too) and i need to convert updated data list again to jsonobject

my json string is

  {
    "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"
              }
            ]
          }
        ]
      }
    ]
  }
like image 848
Thilina Dinith Fonseka Avatar asked Jan 10 '18 03:01

Thilina Dinith Fonseka


People also ask

Can I map a JSON?

You can map the data types of your business model into JSON by using the examples. Data in JSON is either an object or an array. A JSON object is an unordered collection of names and values. A JSON array is an ordered sequence of values.

Can we convert JSON to Java object?

We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.


3 Answers

First of all, you need to create the class that you are going to map JSON inside.

Fortunately, there is a website that can do it for you here


secondly, you can use google Gson library for easy mapping

1. add the dependency.

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

2. from your object to 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. from JSON to object .

        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

for more information about gson see this tutorial.

like image 69
Bishoy Kamel Avatar answered Nov 01 '22 11:11

Bishoy Kamel


If you use JsonObject, you can define your entity class as this:

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

So you can nested to convert your json string to an entity class.

like image 37
yu wang Avatar answered Nov 01 '22 13:11

yu wang


Here is how I do it without any packages, this do the work for me for small use cases:

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

And I have another class to get the json file from assets directory and mapped JsonObject to my model 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;
    }
}

And in my MainActivity -> onCreate:

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

To check that everything working as I want. Here is the json file if you want to check https://github.com/Blasanka/android_quiz_app/blob/sqlite_db_app/app/src/main/assets/quiz_app.json

Regards!

like image 35
Blasanka Avatar answered Nov 01 '22 12:11

Blasanka