这是我制作的一个简单的代码示例,使用org.json库& OkHttp客户端。
它将从服务器中检索JSON,并在TextView中显示每个名字。
注意:我没有测试它,它可能不会编译,但你明白了。
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textViewWrapper"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TextView's will be appended here -->
</LinearLayout>
MyActivity.java
//...other imports
import org.json.*;
import okhttp3.*;
public class MyActivity extends AppCompatActivity {
private LinearLayout textViewWrapper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get TextView Wrapper
textViewWrapper = (LinearLayout) findViewById(R.id.textViewWrapper);
fillTextView();
}
/**
* Fill TextViews with API response.
*
*/
public void fillTextView() {
get("http://example.com/result.php", new Callback() {
@Override
public void onFailure(Call call, IOException e) {}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String body = response.body().string(); //Get API response
//OKHttp callback isn't in the main thread,
//UI operations need to be run in the main thread
//That's why you should use runOnUiThread
MyActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject JSON = null;
try {
//Parse JSON
JSON = new JSONObject(body);
//Get "nametable" array
JSONArray nameTable = JSON.getJSONArray("nametable");
//Loop through "nametable" array
for (int i = 0; i < nameTable.length(); i++) {
JSONObject item = nameTable.getJSONObject(i);
//Create TextView
TextView rowTextView = new TextView(MyActivity.this);
//Set fname
rowTextView.setText(item.getString("fname"));
// add the textview
textViewWrapper.addView(rowTextView);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
/**
* OKHttp GET helper function (You should probably put this in a Request Utils class)
*
*/
public Call get(String url, Callback callback) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.get()
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
}
在这个问题解析JSON的更多信息:How to parse JSON in Java
只是可以肯定,你想显示textView中的“fname”值? –