3

I have api its response like this:

{
"0": "_serialize",
"1": [
    "login"
],
"users": {
    "token": "aaaaa",
    "message": "login successful."
    }
  }

How can I parse this in android using Gson ?

Mohamed AbdelraZek
  • 2,503
  • 4
  • 25
  • 36
Dharmi Patel
  • 55
  • 1
  • 6
  • You need to use it by using _Iterator_. – Piyush Dec 19 '18 at 05:45
  • can you give me example? – Dharmi Patel Dec 19 '18 at 05:47
  • i think it can be used the model class, but using dynamic keys are not ideal for json format, u can replace "0", "1" by constant key – kuber singh Dec 19 '18 at 05:47
  • 2
    Use [this link](http://www.jsonschema2pojo.org/) here paste your raw JSON, select GSON in Annotation Style and get the relevant POJO classes on the click of the preview. – Aseem Sharma Dec 19 '18 at 05:47
  • use @AseemSharma link to generate model class, but i will cause problem if "0" and "1" are not constant keys – kuber singh Dec 19 '18 at 05:49
  • @kubersingh that should be mentioned at first, I cannot assume it not to be a constant. – Aseem Sharma Dec 19 '18 at 05:53
  • @AseemSharma, exactly, I am not with the problem, I m just supporting your words, just telling Dharmi that it may cause the problem if they are not constant keys – kuber singh Dec 19 '18 at 05:56
  • JSON should have pre-defined set of keys to be parsed without probem. If your JSON may have other keys than 0 and 1, then it is not well-structured for parsing, and it is the server-side which should be changer to return you the JSONArray instead of object with 0,1,2,3,4,... keys. – Vladyslav Matviienko Dec 19 '18 at 06:00
  • Possible duplicate of [JSON parsing using Gson for Java](https://stackoverflow.com/questions/5490789/json-parsing-using-gson-for-java) – Martin Zeitler Dec 19 '18 at 06:21
  • @Dharmi-Patel Feel free to accept and vote the correct answer if it helped you out. – Mahdi-Malv Feb 28 '19 at 07:15

4 Answers4

3

Create a pojo of your Json. you can do so with many resources available online like this or this.

Now use below format.

Gson gson = new Gson();
MyPojo myPojo = new MyPojo();
Type collectionType = new TypeToken<MyPojo>() {
                    }.getType();
myPojo = gson.fromJson(responseJson,
                            collectionType);

Hope this helps.

Molly
  • 1,887
  • 3
  • 17
  • 34
2

First of all make model classes from your json using tools like this one. Just copy your json and get the objects.

Let's suppose you call the class Model

Then use this code to get object from your json.

String json = "that-json";
Model m = gson.fromJson(json, Model.class);

More on Gson's guides.

Mahdi-Malv
  • 16,677
  • 10
  • 70
  • 117
1

Generate the Model class from the response

    public void onResponse(String response) {   
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(response);

        YourModelClass objModel = gson.fromJson(jsonObject.getJSONObject("data").toString(), YourModelClass.class);

 } catch (JSONException e) {
    e.printStackTrace();
  }
}
Aseem Sharma
  • 1,673
  • 12
  • 19
1

use gson and map your response to Java Model class.

This will be your model class ->

User.java Model class.

import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang.builder.ToStringBuilder;

public class Users implements Serializable
{

    @SerializedName("token")
    @Expose
    private String token;
    @SerializedName("message")
    @Expose
    private String message;
    private final static long serialVersionUID = 3387741697269012981L;

    /**
     * No args constructor for use in serialization
     * 
     */
    public Users() {
    }

    /**
     * 
     * @param message
     * @param token
     */
    public Users(String token, String message) {
        super();
        this.token = token;
        this.message = message;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public Users withToken(String token) {
        this.token = token;
        return this;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Users withMessage(String message) {
        this.message = message;
        return this;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this).append("token", token).append("message", message).toString();
    }

}

this is your root/parent class, from where parsing starts.

import java.io.Serializable;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang.builder.ToStringBuilder;

public class Root implements Serializable
{

    @SerializedName("0")
    @Expose
    private String _0;
    @SerializedName("1")
    @Expose
    private List<String> _1 = null;
    @SerializedName("users")
    @Expose
    private Users users;
    private final static long serialVersionUID = 5880229946098431789L;

    /**
     * No args constructor for use in serialization
     * 
     */
    public Example() {
    }

    /**
     * 
     * @param users
     * @param _0
     * @param _1
     */
    public Example(String _0, List<String> _1, Users users) {
        super();
        this._0 = _0;
        this._1 = _1;
        this.users = users;
    }

    public String get0() {
        return _0;
    }

    public void set0(String _0) {
        this._0 = _0;
    }

    public Example with0(String _0) {
        this._0 = _0;
        return this;
    }

    public List<String> get1() {
        return _1;
    }

    public void set1(List<String> _1) {
        this._1 = _1;
    }

    public Example with1(List<String> _1) {
        this._1 = _1;
        return this;
    }

    public Users getUsers() {
        return users;
    }

    public void setUsers(Users users) {
        this.users = users;
    }

    public Example withUsers(Users users) {
        this.users = users;
        return this;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this).append("_0", _0).append("_1", _1).append("users", users).toString();
    }

}

now at the code where you receive Json map json to this root/parent class from where parsing starts.

Root root = new Gson().fromJson(/*put your json response variable here*/, Root.class);

and use root object to fetch/set any data via public get methods.

Jay Dangar
  • 3,271
  • 1
  • 16
  • 35