【问题标题】:storing JsonElement in arraylist causes error将 JsonElement 存储在 arraylist 中会导致错误
【发布时间】:2016-01-09 15:16:55
【问题描述】:
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());
}

试图将 JsonObjects 存储到 ArrayList 中,但是在 obj 下的行中出现错误

for(JsonElement jsx: obj)

foreach 不适用于类型 'com.google.gson.JsonElement

如何解决这个问题?

【问题讨论】:

  • 你的 json 输出在哪里??
  • 不能遍历json对象,从json对象中获取json数组然后申请每个循环

标签: java android gson


【解决方案1】:

您可以轻松地将JSONArray 读取为JSONArray 所代表的类型类的ArrayList。感谢GSON 整个过程可以在一行代码中完成。如下图。

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

假设你得到了MyItem 类型的JSONArray,上面的代码行会将JSONArray 转换为ArrayList 类型的MyItem

我已经写了一个示例代码,你可能会得到一个更好的画面。

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

输出

[
  {
    "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"
  }
]

这个JSONArray被转换成ArrayList类型的MyItem

我还写了一些关于这个主题的答案,您可能想使用GSON 库查看有关serializationde-serialization 的更多信息

Example_1

Example_2

Example_3

Example_4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多