Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

      }

    }
}
share|improve this question

3 Answers

up vote 4 down vote accepted
  • use GSON to format the string as JsonArray
  • then traverse the JsonArray to get the values

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("*********");
}
share|improve this answer
Thank you! Works like a charm – Tiffany Jul 16 '12 at 13:49
I do have one question though - is there a way to get the json string without having to hard code it like that? – Tiffany Jul 16 '12 at 13:55
1  
try the getJson function in the code sample that i gave as an answer, in the following post : stackoverflow.com/questions/11471884/…. Using that, you can download json data from external servers – sunil Jul 16 '12 at 16:21

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();
share|improve this answer

I have used org.json.simple.JSONObject and org.json.simple.JSONArray, and I hope net.sf.json.JSONArray also work same.

You should put following string format for output (JSONArray array = new JSONArray(output); )

 {"YOUR_ARRAY_NAME": [{"username":"Hello","email":"[email protected]","credits":"100","twitter_username":""},{"username":"Goodbye","email":"[email protected]","credits":"0","twitter_username":""}]}

Now this is String representation of JSONArray.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.