英文:
Android JAVA : Convert org.json.JSONArray to java.lang.String[]
问题
我正在开发一个Android应用程序,其中在从服务器同步日期时,数据以JSON字符串的形式接收,首先使用以下代码将其转换为JSONObject:
JSONObject jsonObject = new JSONObject("jsonStringFromServer");
而这个jsonObject
包含了许多key:value
对,其中value
的格式是JSONArray
,例如:
{
"id1": ["stringa1", "stringa2", "stringa3"],
"id2": ["stringb1", "stringb2", "stringb3"],
"id3": ["stringc1", "stringc2", "stringc3"]
}
我需要将这个JSONArray
转换成一个简单的String[]
。当我尝试使用(String[]) jsonObject.get("id1")
进行强制转换时,出现错误java.lang.ClassCastException: org.json.JSONArray cannot be cast to java.lang.String[]。
我查找了一些资料,但并没有找到类似于将ArrayList<String>
转换为String[]
的简单解决方案。非常感谢您的帮助。
英文:
I am working an Android app where when synchronising the date from server, data is received as json string, which is being first converted into JSONObject using
JSONObject jsonObject = new JSONObject("jsonStringFromServer")
and this jsonObject
has a bunch of key:value
sets, where value
is in the form of JSONArray
, like
{"id1":["stringa1","stringa2","stringa3"], "id2":["stringb1","stringb2","stringb3"], "id3":["stringc1","stringc2","stringc3"]}
etc
I need convert this JSONArray
into a simple String[]
, and when I tried casting using simple (String[]) jsonObject.get("id1")
, I get this error java.lang.ClassCastException: org.json.JSONArray cannot be cast to java.lang.String[]
I looked around, but have not been able to find a simple solution similar to how a ArrayList<String> can be converted into String[] in java. Any will he highly appreciated
答案1
得分: 1
一个 JsonArray 与 Java 的数组不同。你不能通过转换来将 JsonArray 强制转换为普通的 Java 数组。你可以通过遍历 JsonArray,将其中的对象提取到普通的 Java 数组中。
英文:
A JsonArray is not same as a Java's array. You cannot convert a JsonArray to regular Java arrays by casting. What you can do is, extract objects from the JsonArray into a regular Java array by iterating over JsonArray.
答案2
得分: 1
可以使用流来从 JSON 数组中收集数据,根据您的需求修改代码。下面的代码应该能给您一个概述。
List<String> values = IntStream.range(0, jsonArray.length())
.mapToObj(i -> array.getJSONObject(i).get("key").toString()).collect(Collectors.toList());
英文:
You can use streams to collect data from json array, modify the code as per your needs. The code below should give you an overview.
List<String> values = IntStream.range(0, jsonArray.length())
.mapToObj(i -> array.getJSONObject(i).get("key").toString()).collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论