java 中将list中的string转换成jsonobject
时间: 2023-08-04 21:08:12 浏览: 118
要将List中的String转换为JSONObject,您需要使用JSON库。以下是一个示例代码:
```java
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("Hello");
stringList.add("World");
JSONArray jsonArray = new JSONArray();
for (String str : stringList) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("string", str);
} catch (JSONException e) {
e.printStackTrace();
}
jsonArray.put(jsonObject);
}
System.out.println(jsonArray.toString());
}
}
```
在这个示例中,我们首先创建了一个包含两个字符串的列表。然后,我们使用JSONArray和JSONObject类将每个字符串转换为JSONObject并将其添加到JSONArray中。最后,我们使用toString方法将JSONArray转换为字符串并打印出来。
阅读全文
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)