我的json看起来像这样:
[{
"id":14,
"namelanguage1":"Książka",
"namelanguage2":"das Buch",
"tags":
[{
"id":2,
"name":"Szkoła",
"language_user_id":null,
"created_at":"2014-04-11T17:30:28.356Z",
"updated_at":"2014-04-11T17:30:28.356Z",
"user_id":2
}],
"language1_id":5,
"language2_id":1,
},
{
"id":15,
"namelanguage1":"das Fußball",
"namelanguage2":"Piłka nożna",
"tags":[{
"id":2,
"name":"Szkoła",
"language_user_id":null,
"created_at":"2014-04-11T17:30:28.356Z",
"updated_at":"2014-04-11T17:30:28.356Z",
"user_id":2
},
{
"id":3,
"name":"Sport",
"language_user_id":null,
"created_at":"2014-04-11T17:30:33.059Z",
"updated_at":"2014-04-11T17:30:36.769Z",
"user_id":2
}],
"language1_id":1,
"language2_id":5,
}]
我不知道如何获取标签ID。现在我有了这个:
public class Word {
@SerializedName("id")
public long id;
@SerializedName("namelanguage1")
public String nameLanguage1;
@SerializedName("namelanguage2")
public String nameLanguage2;
@SerializedName("language1_id")
public long language1_id;
@SerializedName("language2_id")
public long language2_id;
public ArrayList<Tag> tags;
和它的吸气剂和制定者。我不知道如何获取标签的ID。我尝试理解这个例子:example from stackoverflow但我仍然不知道如何做到这一点。
我在代码中的表现如何:
words = VolleyDemoApplication.obtain().getGson()
.fromJson(response, new TypeToken<ArrayList<Word>>() {
}.getType());
我从这样的词中得到了值:
word.getNameLanguage1() + " " +word.getLanguage1_id() + " " + word.getNameLanguage2()+ " " + word.getLanguage2_id() + " " + word.getTags().
这里word.getTags().
我不知道写什么。
答案 0 :(得分:0)
有几件事需要指出,我不知道为什么这个代码适合你,当你打印的json不正确时。
实际格式为:
[
{
"id": 14,
"namelanguage1": "aaa",
"namelanguage2": "das Buch",
"tags": [
{
"id": 2,
"name": "bbb",
"language_user_id": null,
"created_at": "2014-04-11T17:30:28.356Z",
"updated_at": "2014-04-11T17:30:28.356Z",
"user_id": 2
}
],
"language1_id": 5,
"language2_id": 1 ->> remove the comma here thats in your json text
},
{
"id": 15,
"namelanguage1": "zzz",
"namelanguage2": "yyy",
"tags": [
{
"id": 2,
"name": "ccc",
"language_user_id": null,
"created_at": "2014-04-11T17:30:28.356Z",
"updated_at": "2014-04-11T17:30:28.356Z",
"user_id": 2
},
{
"id": 3,
"name": "Sport",
"language_user_id": null,
"created_at": "2014-04-11T17:30:33.059Z",
"updated_at": "2014-04-11T17:30:36.769Z",
"user_id": 2
}
],
"language1_id": 1,
"language2_id": 5 ->> remopve the comma here too
}
]
对于SerializedName
arraylist,类字需要tags
。
@SerializedName(value="tags")
public ArrayList<Tag> tags;
您还需要创建标签类:
public class Tag {
@SerializedName(value="id")
private int id;
@SerializedName(value="name")
private String tagName;
@SerializedName(value="language_user_id")
private String languageUserId;
@SerializedName(value="created_at")
private String createdAt;
@SerializedName(value="updated_at")
private String updatedAt;
@SerializedName(value="user_id")
private int userId;
// create getters and setters or else change the modifiers to public
}
您将在Tag
类中访问ID,如下所示:
words.get(0).tags.get(0).getId(); ->> i am using 0 since its the first element, you will need a loop for this
或
words.get(0).tags.get(0).id;
希望有所帮助。