我的布局中有2个带有id(matricula,nome)的TextView,我需要从这个json request获取此值。
我在制作json请求时遇到困难,如get值,这里有一个例子我将如何在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 :(得分: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。