I'm new to JSON and REST. I'm working with a server that returns strings like these:
[{"username":"Hello","email":"[email protected]","credits":"100","twitter_username":""},{"username":"Goodbye","email":"[email protected]","credits":"0","twitter_username":""}]
I've managed to print them out as strings on the console, but now I want to convert them into a JSON array. The code I have so far returns no errors, but I don't know what to put into the constructor for the new JSON array. I've been referring to a piece of code sent to me by a colleague, in which the constructor was new JSONArray(response) but he never told me what 'response' was.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import sun.misc.BASE64Encoder;
public class NetClientGet {
public static void main(String[] args) {
try {
URL url = new URL("http://username:[email protected]/index.php/api/users/get_users/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BASE64Encoder enc = new sun.misc.BASE64Encoder();
String userpassword = "username:password";
String encoded = enc.encode(userpassword.getBytes());
conn.setRequestProperty("Authorization", "Basic " + encoded);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
JSONArray array = new JSONArray(output);
for (int i =0; i < array.size(); i++) {
JSONObject row = array.getJSONObject(i);
String user = row.getString("username");
System.out.println(user);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Approach 1: First convert the JSON string to the JavaScript object using JSON. Parse() method and then take out the values of the object and push them into the array using push() method.
String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.
the code sample
String json = "[{\"username\":\"Hello\",\"email\":\"[email protected]\",\"credits\":\"100\",\"twitter_username\":\"\"},{\"username\":\"Goodbye\",\"email\":\"[email protected]\",\"credits\":\"0\",\"twitter_username\":\"\"}]";
JsonArray jArray = new JsonParser().parse(json).getAsJsonArray();
for (int i=0;i<jArray.size();i++) {
JsonObject jsonObject = jArray.get(i).getAsJsonObject();
System.out.println(jsonObject.get("username"));
System.out.println(jsonObject.get("email"));
System.out.println(jsonObject.get("credits"));
System.out.println(jsonObject.get("twitter_username"));
System.out.println("*********");
}
I am using gson library to manipulate json. You can download gson from here. It is a very good library to handle json. Create json parser first, it will parse the json string:
JsonParser parser = new JsonParser();
now initialize an empty json array
JsonArray jArray = new JsonArray();
Now use the parser to create json array
jArray = parser.parse(outputString).getAsJsonArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With