Java 将字符串转化为JSONObject - 示例代码与解析
要将 "[{"result":0,"code":1,"serial":831,"headSerial":1}]" 转化为 JSONObject,可以使用 JSON 库来实现。以下是一个示例代码:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonArrayString = "[{"result":0,"code":1,"serial":831,"headSerial":1}]";
try {
JSONArray jsonArray = new JSONArray(jsonArrayString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
System.out.println(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
在上面的代码中,我们首先创建了一个 JSONArray 对象,然后从该数组中获取第一个元素,即 JSONObject。最后,我们将该 JSONObject 打印出来。
输出结果为:
{"result":0,"code":1,"serial":831,"headSerial":1}
注意:在使用这段代码之前,需要先下载并导入 JSON 库,比如使用 org.json 库。
原文地址: https://www.cveoy.top/t/topic/pOhO 著作权归作者所有。请勿转载和采集!