我是新来的JSON和REST。 我与返回喜欢这些字符串的服务器的工作:
[{"username":"Hello","email":"hello@email.com","credits":"100","twitter_username":""},{"username":"Goodbye","email":"goodbye@email.com","credits":"0","twitter_username":""}]
我已经成功地打印出来作为在控制台上琴弦,但现在我想将它们转换成JSON阵列。 我到目前为止的代码返回没有错误,但我不知道该怎么投入构造新JSON阵列。 我一直指由同事发给我的一段代码,在这种构造是新JSONArray(响应),但他从来没有告诉我是什么“的反应”了。
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:password@mobile.crowdedmedia.co.uk/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();
}
}
}