0
Gson gson = new Gson();
JsonParser parser = new JsonParser();

JsonElement obj = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonObject();

for(JsonElement jsx: obj) {
  MainPojo cse = gson.fromJson(jsx, MainPojo.class);
  TweetList.add(cse);
  Log.w("F:", "" + TweetList.get(0).getStatuses().get(0).getScreenName());
}

Trying to store JsonObjects into an ArrayList, however I get an error in the line under obj

for(JsonElement jsx: obj) saying

foreach not applicable to type 'com.google.gson.JsonElement

How to fix this?

wogsland
  • 9,106
  • 19
  • 57
  • 93
OBX
  • 6,044
  • 7
  • 33
  • 77

1 Answers1

0

you can easily read JSONArray into ArrayList of type class to which JSONArray is representing. Thank is GSON this entire process can be done in a single line of code. as shown bellow.

ArrayList<MyItem> items2 = (new Gson()).fromJson(result,new TypeToken<ArrayList<MyItem>>() {}.getType());

Lets assume you are given with a JSONArray of type MyItem above line of code will convert JSONArray into the ArrayList of type MyItem.

I have written a sample code, that you may get a better picture.

import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class MyTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<MyItem> items = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            MyItem item = new MyItem();
            item.setRate("rate_"+i);
            item.setSomeCode("some_"+i);
            items.add(item);
        }

        String result = (new Gson()).toJson(items);

        System.out.println(""+result);

        ArrayList<MyItem> items2 = (new Gson()).fromJson(result,new TypeToken<ArrayList<MyItem>>() {}.getType());

        System.out.println(""+items2.size());
    }
}

class MyItem {
    private String rate;
    private String someCode;

    public String getRate() {
        return rate;
    }

    public void setRate(String rate) {
        this.rate = rate;
    }

    public String getSomeCode() {
        return someCode;
    }

    public void setSomeCode(String someCode) {
        this.someCode = someCode;
    }
}

Output

[
  {
    "rate": "rate_0",
    "someCode": "some_0"
  },
  {
    "rate": "rate_1",
    "someCode": "some_1"
  },
  {
    "rate": "rate_2",
    "someCode": "some_2"
  },
  {
    "rate": "rate_3",
    "someCode": "some_3"
  },
  {
    "rate": "rate_4",
    "someCode": "some_4"
  }
]

this JSONArray is converted into ArrayList of type MyItem

I have also written some answers on this topic which you may want to check for further information on serialization and de-serialization using GSON library

Example_1

Example_2

Example_3

Example_4

Community
  • 1
  • 1
Pankaj Nimgade
  • 4,529
  • 3
  • 20
  • 30