2013-08-18 70 views
-1

我的佈局中有2個TextView,其ID爲(matricula,nome),我需要從此json request獲取此值。如何從URL中獲取內容並解析json

我有兩個difficults使JSON請求中獲取值,這裏是一個例子,我將如何在PHP和jQuery做:

PHP

$alunos = json_decode("let's pretend json data is here"); 

echo "Matricula: " . $alunos['Aluno']['matricula']; 
echo "Nome: " . $alunos['Aluno']['nome']; 

jQuery的

var alunos = $.parseJSON("let's pretend json data is here"); 

console.log("Matricula: " + alunos.aluno.matricula); 
console.log("Nome: " + alunos.aluno.nome); 

幫助:
Aluno =學生
Matricula =學生編號
Nome = name

我在這裏閱讀了一些關於解析json的答案,但我承認它很難理解。

+0

你需要通過php或java解析它嗎? –

+0

JAVA,php只是一個例子 –

回答

1

這也很容易在Java中(我離開了所有的錯誤處理專注於主流程,請補充說明自己):

import org.json.JSONObject; 
import java.net.URL; 
import java.net.HttpURLConnection; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

... 

private String readString(Reader r) throws IOException { 
    char[] buffer = new char[4096]; 
    StringBuilder sb = new StringBuilder(1024); 
    int len; 
    while ((len = r.read(buffer)) > 0) { 
     sb.append(buffer, 0, len); 
    } 
    return sb.toString(); 
} 

... 

// fetch the content from the URL 
URL url = new URL("http://..."); // add URL here 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
InputStreamReader in = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
String jsonString = readString(in); 
in.close(); 
conn.disconnect(); 

// parse it and extract values 
JSONObject student = new JSONObject(jsonString); 
String id = student.getJSONObject("Aluno").getString("matricula"); 
String name = student.getJSONObject("Aluno").getString("nome"); 

有關詳情請參閱documentation

+0

什麼是「theJsonString」? –

+0

就像你的''讓我們假裝json數據在這裏吧'' – Henry

+0

但我不知道如何解析Java中的json ... –