My json response is below
{
"groups":[
{
"storeId":"440f0991-9ac5-41b9-9e84-d3b2a2d27c13",
"name":"oty",
"description":"ga",
"image":null,
"bookCount":2,
"members":[
{
"bookId":"9b765d0f-3d6f-4fc1-a4a7-af807c39a004",
"bookName":"Anantha"
},
{
"bookId":"f8616ab1-eeb3-403b-8182-b42e39f4b948",
"bookName":"lok"
}
]
}
]
}
My code for parsing json
JSONObject jsonObject = new JSONObject(message);
JSONArray jsonArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < jsonArray.length(); i++) {
String storeid = jsonArray.getJSONObject(i).getString("storeId");
String name = jsonArray.getJSONObject(i).getString("name");
String description =jsonArray.getJSONObject(i).getString("description");
String bookCount = jsonArray.getJSONObject(i).getString("bookCount");
JSONArray memberJsonArray = jsonArray.getJSONObject(i).getJSONArray("members");
for (int j = 0; j < memberJsonArray.length(); j++) {
String bookId = memberJsonArray.getJSONObject(j).getString("bookId");
String bookName = memberJsonArray.getJSONObject(j).getString("bookName")
GroupsDto groupDtoData = new GroupsDto();
groupDtoData.setGroupName(name);
groupDtoData.setGroupServerId(storeId);
groupDtoData.setbookname(bookName);
groupDtoData.setbookid(bookId);
groupDto.add(groupDtoData);
db.addGroups(groupDtoData);
}
}
but I got result as if book name is twice then the storeId is also twice.simillarly increse in no of book name,store id also increse.so it reflect on the list view having duplicate store name.
I/System.out: storeId 440f0991-9ac5-41b9-9e84-d3b2a2d27c13
I/System.out: bookName Ananta
I/System.out: storeId groupid440f0991-9ac5-41b9-9e84-d3b2a2d27c13
I/System.out: bookname Lok
但是我想要一个storeId有两个书名,但商店ID也要两次 请介绍一下如何解析这种类型的json。我已经面临json解析这个问题但是我想要一个storeId有两个书名但商店id也得到两次
答案 0 :(得分:1)
使用Gson进行序列化和反序列化。 1.创建一个模型类,您的情况将如下所示。
public class MyResponse {
@SerializedName("groups")
private List<Groups> groupsList;
public List<Groups> getGroupsList() {
return groupsList;
}
public class Groups {
@SerializedName("storeId")
private String storeId;
@SerializedName("name")
private String name;
@SerializedName("description")
private String description;
@SerializedName("bookCount")
private String bookCount;
@SerializedName("members")
private List<Members> members;
public String getStoreId() {
return storeId;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getBookCount() {
return bookCount;
}
public List<Members> getMembers() {
return members;
}
public class Members {
@SerializedName("bookId")
private String bookId;
@SerializedName("bookName")
private String bookName;
public String getBookName() {
return bookName;
}
public String getBookId() {
return bookId;
}
}
}
}
如果使用android studio
,请确保在gradle文件中添加Gson Lib依赖{ 编译'com.google.code.gson:gson:2.6.2' }
使用响应字符串,对于您的情况是消息对象,并将其转换为如下所示的响应对象。
Gson gson = new GsonBuilder()。create();
MyResponse myResponse = gson.fromJson(message,MyResponse.class);