Android JAVA: 将 org.json.JSONArray 转换为 java.lang.String[]

huangapple go评论74阅读模式
英文:

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(&quot;jsonStringFromServer&quot;) and this jsonObject has a bunch of key:value sets, where value is in the form of JSONArray, like
{&quot;id1&quot;:[&quot;stringa1&quot;,&quot;stringa2&quot;,&quot;stringa3&quot;], &quot;id2&quot;:[&quot;stringb1&quot;,&quot;stringb2&quot;,&quot;stringb3&quot;], &quot;id3&quot;:[&quot;stringc1&quot;,&quot;stringc2&quot;,&quot;stringc3&quot;]} etc

I need convert this JSONArray into a simple String[], and when I tried casting using simple (String[]) jsonObject.get(&quot;id1&quot;), 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&lt;String&gt; values = IntStream.range(0, jsonArray.length())
				.mapToObj(i -&gt; array.getJSONObject(i).get(&quot;key&quot;).toString()).collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年7月25日 13:12:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63084614.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定