Kemat Rochi Kemat Rochi - 7 months ago 12
Java Question

How to extract data from this JSON?

I have the following JSON Array as a string like this,

String output = "[{\"Symbol\":\"AMZN\",\"Name\":\"Amazon.com Inc\",\"Exchange\":\"NASDAQ\"},{\"Symbol\":\"VXAZN\",\"Name\":\"CBOE Amazon VIX Index\",\"Exchange\":\"Market Data Express\"}]";


I want to parse it and make a string array like this,

array = {"AMZN Amazon.com Inc NASDAQ", "VXAZN CBOE Amazon VIX Index Market Data Express"};


I came up with the following code to parse the string into a JSON Array using the
json-simple-1.1.1.jar
library,

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);
}
}


This gives me the following OUTPUT,

[{"Name":"Amazon.com Inc","Exchange":"NASDAQ","Symbol":"AMZN"},{"Name":"CBOE Amazon VIX Index","Exchange":"Market Data Express","Symbol":"VXAZN"}]


Now after this, is there an elegant way to achieve my desired output?

Answer

You have to write extra code.

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
Comments