2012-07-16 149 views
5

我是JSON和REST的新手。我與返回一個字符串像這樣的一臺服務器的工作:REST和JSON - 將字符串轉換爲JSON數組

[{"username":"Hello","email":"[email protected]","credits":"100","twitter_username":""},{"username":"Goodbye","email":"[email protected]","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:[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(); 

     } 

    } 
} 

回答

11
  • 使用GSON字符串格式化爲JsonArray
  • 然後遍歷JsonArray得到的值

的代碼示例

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("*********"); 
} 
+0

謝謝!像魅力一樣工作 – Tiffany 2012-07-16 13:49:43

+0

我確實有一個問題 - 有沒有辦法讓json字符串不必像這樣硬編碼? – Tiffany 2012-07-16 13:55:48

+1

嘗試在我給出的代碼示例中的getJson函數作爲答案,在下面的帖子中:http://stackoverflow.com/questions/11471884/need-help-android-json-currency-converter/11472677#11472677。使用它,您可以從外部服務器下載json數據 – sunil 2012-07-16 16:21:14

1

我正在使用gson庫來操縱json。你可以從here下載gson。這是一個處理json的非常好的庫。 創建JSON解析器首先,它將解析JSON字符串:

JsonParser parser = new JsonParser(); 

現在初始化一個空的JSON數組

JsonArray jArray = new JsonArray(); 

現在使用的解析器創建JSON數組

jArray = parser.parse(outputString).getAsJsonArray(); 
0

我有使用org.json.simple.JSONObject和org.json.simple.JSONArray,我希望net.sf.json.JSONArray也可以工作。

你應該把下面的字符串格式爲輸出(JSONArray陣列=新JSONArray(輸出);)

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

現在這是JSONArray的字符串表示。