Nuha
Nuha

Reputation: 324

Storing JSON array in different lists or arrays

{
    "status": true,
    "message": [
        {
            "ID": 1,
            "TFrom": "b",
            "TTo": "c"
        },
        {
            "ID": 2,
            "TFrom": "b",
            "TTo": "c"
        },
        {
            "ID": 3,
            "TFrom": "b",
            "TTo": "c"

       }
    ]
}

This is my JSON result, I'm using Android/Java and what I want is to get each object in the "message" array separated in an array, because each one of them should be in a list item. Which means my ListView is going to view the "message" content in lists. It's more like this:

list1= [{"ID": 1, "TFrom": "b", "TTo": "c"}] 
list2= [{"ID": 2, "TFrom": "b", "TTo": "c"}] 

Upvotes: 0

Views: 2736

Answers (5)

Himanshu itmca
Himanshu itmca

Reputation: 395

Try this

    List<Map<String,String>> list = new ArrayList<>();
    try
    {
        JSONArray messageArray = response.getJSONArray("message");
        for (int i = 0;i<messageArray.length(); i++)
        {
            Map<String,String> map = new HashMap<>();
            JSONObject jsonObject = messageArray.getJSONObject(i);
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext())
            {
                String key = keys.next();
                String value = jsonObject.getString(key);
                map.put(key,value);
            }
            list.add(map);
        }
    }
    catch (JSONException e) 
    {
        e.printStackTrace();
    }

Upvotes: 0

Gopal
Gopal

Reputation: 36

Use gson library. check below how to implement in project.

build.gradle

implementation 'com.google.code.gson:gson:2.7'

Then create MessageModel.java and MessageBaseModel.java.

MessageModel.java

public class MessageModel {
@SerializedName("ID")
int id;

@SerializedName("TFrom")
String tFrom;

@SerializedName("TTo")
String tTo;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String gettFrom() {
    return tFrom;
}

public void settFrom(String tFrom) {
    this.tFrom = tFrom;
}

public String gettTo() {
    return tTo;
}

public void settTo(String tTo) {
    this.tTo = tTo;
}
}

MessageBaseModel.java

public class MessageBaseModel {
@SerializedName("status")
boolean status;

@SerializedName("message")
ArrayList<MessageModel> messageModels = new ArrayList<>();

public boolean isStatus() {
    return status;
}

public void setStatus(boolean status) {
    this.status = status;
}

public ArrayList<MessageModel> getMessageModels() {
    return messageModels;
}

public void setMessageModels(ArrayList<MessageModel> messageModels) {
    this.messageModels = messageModels;
}
}

Use below code in your main activity:(note: result is your JSON result)

MessageBaseModel messageBaseModel=new Gson().fromJson(result.toString() , MessageBaseModel.class);
ArrayList<MessageModel> messageModels =  MessageBaseModel.getMessageModels();

Check below example to get the output:

messageModels.get(0) is your first message object

messageModels.get(0).getId()=1

messageModels.get(0).gettFrom()=b

messageModels.get(1).getId()=2

messageModels.get(2).getId()=3

Sorry for my english.

Upvotes: 0

ankur uniyal
ankur uniyal

Reputation: 86

 JSONObject heroObject = data.getJSONObject("favorite");
JSONArray jarray=heroObject.getJSONArray("message");
ArrayList<HashMap<String,String>> array=new ArrayList<>();
                        //now looping through all the elements of the json array 
                        for (int i = 0; i < jarray.length(); i++) {
                            //getting the json object of the particular index inside the array
                          JSONObject heroObject = jarray.getJSONObject(i);
HashMap<String,String> inner=new HashMap<String, String>();
inner.put("id", heroObject.getString("ID"));
inner.put("from", heroObject.getString("TFrom"));
inner.put("to", heroObject.getString("TTo"));
                              array.add(inner);

                        }

Upvotes: 0

Jawad Zeb
Jawad Zeb

Reputation: 523

Message Object Class:

public class MessagesObject {
    boolean status;
    List<AMessage> message;

    public List<AMessage> getMessage() {
        return message;
    }

    public void setMessage(List<AMessage> message) {
        this.message = message;
    }

    public boolean isStatus() {

        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }


}

AMessage Class:

public class AMessage {
    int ID;
    String TFrom;
    String TTo;

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public String getTFrom() {
        return TFrom;
    }

    public void setTFrom(String TFrom) {
        this.TFrom = TFrom;
    }

    public String getTTo() {
        return TTo;
    }

    public void setTTo(String TTo) {
        this.TTo = TTo;
    }
}

Usage :

String json="you json string";
MessagesObject messagesObject = new Gson().fromJson(jsonToParse, MessagesObject.class);

Ref Gson :

implementation 'com.google.code.gson:gson:2.8.2'

Output:

enter image description here

Upvotes: 1

christopher_pk
christopher_pk

Reputation: 651

I'm not sure what you really want, but if you really would like to convert an array into list of arrays, ie.

[1, 2, 3] => [[1], [2], [3]]

You can use this code as a starting point.

    List<List<T>> YOUR_LIST_OF_LISTS = message.stream().map((e) -> {
        ArrayList<T> temp = new ArrayList<>();
        temp.add(e);
        return temp;
    }).collect(Collectors.toList());

Replace T with some datatype you want, in your case probably JSONObject.

Not android specific, just java codes. I'm not sure why you would want to do something like this tho. Comment below if this is not what you intended.

Upvotes: 0

Related Questions