2013-08-28 186 views
0

我需要從this url的json獲取這兩個信息「matricula」和「nome」,但我不知道如何做到這一點。我想使用this class是一個不錯的選擇,但我不知道如何使用從url獲取json的方法,並且我不知道如何在獲取json之後使用數組鍵。我很抱歉,我要求你做的全部工作,但是因爲我是新的Android開發,我真的與jsonarray,jsonobjects等困惑。從url獲取json並解析信息

+0

什麼你試過嗎? – Triode

+0

什麼也沒有,因爲我不知道如何處理java上的jsonarray和jsonobject,所以這是開始的問題。 –

+0

試試這個Jackson庫,它可以通過幾行代碼從InputStream中解碼你的實體:http://jackson.codehaus.org/ –

回答

0

JsonObject in像Map Interface在Java:

它存儲與關聯值的關鍵。

實施例:

JsonObject obj = new JsonObject(); 
JsonObject obj1 = new JsonObject(); 
obj1.put("obj1_key1","obj1_value1"); 
obj1.put("obj1_key2","obj1_value2"); 
obj1.put("obj1_key3","obj1_value3"); 
obj.put("obj1",obj1); 

JsonArray是像Java中的List Interface

它存儲與索引值從0到N

實施例:

JsonArray array = new JsonArray(); 
JsonObject obj = new JsonObject(); 
obj.put("xxx","yyy"); 
array.add(obj); 

當想要檢索一個json字符串,請記住,當數組以開頭時你需要使用JsonArray解析它,當陣列{}開始,你需要使用的JSONObject

你可以看到一個例子here

您的JSON

{"matricula":"201110460","nome":"Daniel de Faria Pedro"} 

這僅僅是一個JSONObject因爲它具有經典的「地圖」風格關鍵值關聯。 什麼你簡單的需要做的是:

try { 
    URL url = new URL("http://tcc-teste.aws.af.cm/api/get/aluno/1"); 
    URLConnection connection = url.openConnection(); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
    String line = "", json = ""; 
    while((line = reader.readLine())!=null){ 
     json+=line; 
    }      
    JsonObject yourObject = new JsonObject(json); 
    String matricula = yourObject.get("matricula"); 
    String nome = yourObject.get("nome"); 
    System.out.println(nome+" - "+matricula); 
} catch (MalformedURLException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
+0

抱歉,你能給我一個基於json數據結構的例子嗎?題?讓我們假設我已經從url獲取數據。 –

+0

當然...見編輯請求:) – JackTurky

0

我這樣做:

盤算,你從一個數據庫中的信息有兩列,matricula和諾姆,和我想象你需要發送一個數組所以我會生成具有此代碼的陣列

$json['test'][]=array('matricula' => $row["matricula"], 'nome' =>$row["nome"]) 

然後我會分析這樣的假設,你知道如何得到它是信息:

JSONObject object = new JSONObject(jsonResult); 
JSONArray test = object.getJSONArray("test"); 
for(int i = 0; i < test.length(); i++){ 
    JSONObject c = test.getJSONObject(i); 
    String matricula= c.getString("matricula"); 
    String nome = c.getString("nome"); 
    //do whatever you want with it 
} 
+0

你是什麼意思這個php數組? –

+0

您可以同時從數據庫發送更多行。這就是你如何做JSONArray,然後你可以回顯它。 –

0

你可以看看這個例子/教程中,我使用了原生的Android JSONObjectJSONArray對象解析JSON文件或使用Gson庫中寫道:

Parsing JSON Files