我们可以使用json-simple-1.1.1.jar库将字符串转换为JSON数组吗? [英] Can we convert a string to JSON Array using the json-simple-1.1.1.jar library?
问题描述
我想使用json-simple-1.1.1.jar
库将字符串转换为JSON数组,并提出以下代码,
I want to convert a string into a JSON Array using the json-simple-1.1.1.jar
library and came up with the following code,
import org.json.simple.*;
public class RESTclient {
public static void main(String[] args) {
String output = "[{\"Symbol\":\"AMZN\",\"Name\":\"Amazon.com Inc\",\"Exchange\":\"NASDAQ\"},{\"Symbol\":\"VXAZN\",\"Name\":\"CBOE Amazon VIX Index\",\"Exchange\":\"Market Data Express\"}]";
JSONObject jsonObject = new JSONObject(output);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
System.out.println(jsonArray);
}
}
我希望输出为JSON数组.我在这里做错什么了?
I want the output to be a JSON Array. What am I doing wrong here?
推荐答案
我在这里做什么错了?
您正在尝试将包含JSON数组的String
转换为JSONObject
You're trying to convert a String
that contains a JSON array into a JSONObject
JSONObject jsonObject = new JSONObject(output);
您的内容表示一个JSON数组,因此应这样解析
Your content represents a JSON array so parse it as such
JSONParser parser = new JSONParser();
JSONArray jsonArray = (JSONArray) parser.parse(output);
请注意,其他库,例如Gson和Jackson,对JSON数组和对象(JsonArray
,ArrayNode
)具有更好的抽象性.考虑改用那些.
Note that other libraries, like Gson and Jackson, have much better abstractions for JSON arrays and objects (JsonArray
, ArrayNode
). Consider using those instead.
这篇关于我们可以使用json-simple-1.1.1.jar库将字符串转换为JSON数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!