【问题标题】:How use GSON when JSON doen't have "Name attribute"?当 JSON 没有“名称属性”时如何使用 GSON?
【发布时间】:2014-02-23 20:58:34
【问题描述】:

我有以下 JSON(来自 URL)

["Rock","Rock Argentino","Reggaeton","En Español","Reggaeton ","Reggaeton  ","Boleros","Italianos ","Cumbias ","Cumbia ","Internacional","Internacional "]

您可以看到这些字段没有“名称属性”。

我的班级模型如下

public class KaraokeCategoryModel {
private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

但 GSON 没有重新识别我的属性“名称”

Type karaokeCollection = new TypeToken<Collection<KaraokeCategoryModel>>() {}.getType();
        _karaoke_cartegory_response = new Gson().fromJson(reader, karaokeCollection);

稍后我创建适配器

_karaoke_category_adapter = new KaraokeCategoryAdapter(getSupportActionBar().getThemedContext(), R.layout.spinner_item, _karaoke_cartegory_response);
        getSupportActionBar().setListNavigationCallbacks(_karaoke_category_adapter, this);

我应该怎么做才能让 GSON 使用我的模型没有问题?

【问题讨论】:

  • 为什么不把它读成List&lt;String&gt; 并为每个字符串创建一个KaraokeCategoryModel 对象呢? (您需要为您的类创建一个构造函数。)
  • @ChthonicProject 使用该选项创建适配器是否复杂??
  • 我看不出根据您创建 KaraokeCategoryModel 的方式创建适配器会如何变化。

标签: java android json gson


【解决方案1】:

您可以使用以下代码更轻松地做到这一点:

List<KaraokeCategoryModel> karaokeCategoryList = new ArrayList<KaraokeCategoryModel>();

JsonElement json = new JsonParser().parse(yourJsonStringValueHere);
JsonArray jsonArray = json.getAsJsonArray();
Iterator iterator = jsonArray.iterator();
while(iterator.hasNext()){
    JsonElement jsonElementInArray = (JsonElement)iterator.next();

    KaraokeCategoryModel karaokeCategory = new KaraokeCategoryModel();
    karaokeCategory.setName(jsonElementInArray.getAsString());

    karaokeCategoryList.add(karaokeCategory);    
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
  • 2021-11-24
  • 2016-03-17
  • 2016-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多