Android JSON解析动态按钮
我有一个json格式:Android JSON解析动态按钮,android,json,android-recyclerview,Android,Json,Android Recyclerview,我有一个json格式: [{ "name": "Selection", "link": ["https://d1u5p3l4wpay3k.cloudfront.net/testSelect.ogg"] }, { "name": "Introduction", "link": ["https://d1u5p3l4wpay3k.cloudfront.net/introSelect.ogg", "https://d1u5p3l4wpay3
[{
"name": "Selection",
"link": ["https://d1u5p3l4wpay3k.cloudfront.net/testSelect.ogg"]
},
{
"name": "Introduction",
"link": ["https://d1u5p3l4wpay3k.cloudfront.net/introSelect.ogg",
"https://d1u5p3l4wpay3k.cloudfront.net/introSelect2.ogg".ogg"
]
},
{
"name": "Abilities",
"link": ["https://d1u5p3l4wpay3k.cloudfront.net/testatk1.ogg",
"https://d1u5p3l4wpay3k.cloudfront.net/testatk1.ogg",
"https://d1u5p3l4wpay3k.cloudfront.net/testatk1.ogg",
"https://d1u5p3l4wpay3k.cloudfront.net/testatk1.ogg"
]
}]
我想创建一个活动,其中按钮是根据json中给出的链接创建的,例如,第一个键是1个按钮,第二个键是2,而第三个键是4个按钮
这是我的get_数据()
获得初始JSON数组后,需要查询JSON对象:
JSONObject jsonObject = response.getJSONObject(i);
每次通过循环时,应获得以下类似块:
{"name": "Introduction",
"link": ["https://d1u5p3l4wpay3k.cloudfront.net/introSelect.ogg",
"https://d1u5p3l4wpay3k.cloudfront.net/introSelect2.ogg".ogg"
]}
由于我们知道这是一个我们想要的数组,所以您需要这样做来获取对象的“链接”部分并将其分配给JSONArray:
JSONArray jsonArrayLink = jsonObject.getJSONArray("link");
同样,您可以设置for循环以获取此数组的每个项并将其保存为字符串:
for (int i = 0; i < jsonArrayLink.length(); i++) {
String link = jsonArrayLink.getJSONObject(i).toString();
// do what you want with the string
}
而不是:
String testJSON = jsonObject.getString("test");
这将检查是否有该项,如果没有,则将变量设置为空字符串“”如果什么都没有找到,我就不会创建错误。我不明白问题出在哪里,看起来你正在做你想做的事情?如果不清楚,很抱歉,但我无法创建按钮,这取决于链接数组,而不仅仅是名称。当你从json数组中获取按钮名称时,你能抓取一下吗数组中的下一个元素并将按钮设置为单击该url?你不知道如何使用url吗?即使你说我可能在正确的轨道上,我仍然是新手,我在网上跟随了许多图图来做这件事,如果你能帮我做这件事,我真的很感激,我不能循环通过链接数组,因为我尝试使用另一个“for”,但我得到了一个错误。检查。嘿,谢谢你的代码,但实际上我以前做过这件事,并且遇到了一个异常错误“0的java.lang.String类型无法转换为JSONObject”,您能分享代码和错误吗?
{"name": "Introduction",
"link": ["https://d1u5p3l4wpay3k.cloudfront.net/introSelect.ogg",
"https://d1u5p3l4wpay3k.cloudfront.net/introSelect2.ogg".ogg"
]}
JSONArray jsonArrayLink = jsonObject.getJSONArray("link");
for (int i = 0; i < jsonArrayLink.length(); i++) {
String link = jsonArrayLink.getJSONObject(i).toString();
// do what you want with the string
}
String testJSON = attributes.has("test") ? attributes.getString("test") : "";
String testJSON = jsonObject.getString("test");