我将以下JSON数组作为这样的字符串,
String output = "[{\"Symbol\":\"AMZN\",\"Name\":\"Amazon.com Inc\",\"Exchange\":\"NASDAQ\"},{\"Symbol\":\"VXAZN\",\"Name\":\"CBOE Amazon VIX Index\",\"Exchange\":\"Market Data Express\"}]";
我想解析它并创建一个像这样的字符串数组,
array = {"AMZN Amazon.com Inc NASDAQ", "VXAZN CBOE Amazon VIX Index Market Data Express"};
我想出了以下代码,使用json-simple-1.1.1.jar
库将字符串解析为JSON数组,
import org.json.simple.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
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\"}]";
JSONParser parser = new JSONParser();
JSONArray jsonArray = null;
try {
jsonArray = (JSONArray) parser.parse(output);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(jsonArray);
}
}
这给了我以下 OUTPUT ,
[{"Name":"Amazon.com Inc","Exchange":"NASDAQ","Symbol":"AMZN"},{"Name":"CBOE Amazon VIX Index","Exchange":"Market Data Express","Symbol":"VXAZN"}]
在此之后,是否有一种优雅的方式来实现我想要的输出?
答案 0 :(得分:1)
你必须编写额外的代码。
ArrayList<String> stringArray = new ArrayList<String>();
for (Iterator iterator = jsonArray.iterator(); iterator.hasNext();) {
JSONObject map = (JSONObject)iterator.next();
stringArray.add(map.get("Symbol")+" "+map.get("Name")+" "+map.get("Exchange"));
}
//stringArray is want you want
答案 1 :(得分:0)
你可以和杰克逊一样,
private ObjectMapper mapper = new ObjectMapper();
String[] outputArray = mapper.readValue(jsonString, String[].class);