如何在Android Studio(Java)中解析JSON为表格并仅选取部分内容?
Hey there! Let's walk through exactly how to fetch JSON data from a URL, parse it to extract only the parts you need, and display those selected fields in a table-like format in your Android Java app. Here's a step-by-step breakdown with code examples:
First, add these dependencies to your app-level build.gradle (Module level) to handle network calls, JSON parsing, and flexible table display:
dependencies { // For reliable network requests implementation 'com.squareup.okhttp3:okhttp:4.11.0' // For simplified JSON parsing (easier than native JSONObject) implementation 'com.google.code.gson:gson:2.10.1' // For RecyclerView (to build a responsive table) implementation 'androidx.recyclerview:recyclerview:1.3.2' }
Don't forget to enable internet access in your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
Network operations can't run on the main thread, so we'll use OkHttp's async enqueue method to handle this safely:
private void fetchJsonFromUrl(String targetUrl) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(targetUrl) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); // Show error feedback to user (must run on UI thread) runOnUiThread(() -> Toast.makeText(MainActivity.this, "Failed to load data", Toast.LENGTH_SHORT).show() ); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful() && response.body() != null) { String rawJson = response.body().string(); // Parse and process the JSON, then update UI parseAndExtractNeededFields(rawJson); } } }); }
Let's assume your JSON structure looks like this (adjust to match your actual data):
{ "employees": [ { "id": 101, "name": "Alice Smith", "department": "Engineering", "email": "alice@company.com", "salary": 85000 }, { "id": 102, "name": "Bob Johnson", "department": "Marketing", "email": "bob@company.com", "salary": 72000 } ] }
Suppose you only need id, name, and department fields. First create a model class to hold this extracted data:
public class Employee { private int id; private String name; private String department; // Getters (required for Gson to map fields) public int getId() { return id; } public String getName() { return name; } public String getDepartment() { return department; } }
Now parse the JSON and extract your target fields using Gson:
private void parseAndExtractNeededFields(String rawJson) { JsonObject rootObj = new JsonParser().parse(rawJson).getAsJsonObject(); JsonArray employeesArray = rootObj.getAsJsonArray("employees"); Gson gson = new Gson(); List<Employee> filteredEmployees = new ArrayList<>(); for (JsonElement element : employeesArray) { // Gson automatically ignores fields not present in our Employee class Employee employee = gson.fromJson(element, Employee.class); filteredEmployees.add(employee); } // Update UI with the filtered data (must run on main thread) runOnUiThread(() -> displayAsTable(filteredEmployees)); }
If you prefer using native JSONObject (no external library), here's an alternative approach:
private void parseWithNativeJson(String rawJson) throws JSONException { JSONObject rootObj = new JSONObject(rawJson); JSONArray employeesArray = rootObj.getJSONArray("employees"); List<Employee> filteredEmployees = new ArrayList<>(); for (int i = 0; i < employeesArray.length(); i++) { JSONObject empObj = employeesArray.getJSONObject(i); Employee employee = new Employee(); // Manually extract only the fields you need employee.setId(empObj.getInt("id")); employee.setName(empObj.getString("name")); employee.setDepartment(empObj.getString("department")); filteredEmployees.add(employee); } runOnUiThread(() -> displayAsTable(filteredEmployees)); }
We'll use RecyclerView with a grid layout to create a table-like view. First, create a row layout (item_table_row.xml):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="8dp" android:weightSum="3"> <TextView android:id="@+id/tv_id" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="14sp" android:textStyle="bold"/> <TextView android:id="@+id/tv_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="14sp"/> <TextView android:id="@+id/tv_dept" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="14sp"/> </LinearLayout>
Create a header layout (item_table_header.xml) for column titles:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="8dp" android:weightSum="3" android:background="#f5f5f5"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="ID" android:textSize="16sp" android:textStyle="bold"/> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Name" android:textSize="16sp" android:textStyle="bold"/> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Department" android:textSize="16sp" android:textStyle="bold"/> </LinearLayout>
Now build the RecyclerView Adapter:
public class EmployeeTableAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int VIEW_TYPE_HEADER = 0; private static final int VIEW_TYPE_ROW = 1; private List<Employee> employeeList; public EmployeeTableAdapter(List<Employee> employeeList) { this.employeeList = employeeList; } @Override public int getItemViewType(int position) { return position == 0 ? VIEW_TYPE_HEADER : VIEW_TYPE_ROW; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); if (viewType == VIEW_TYPE_HEADER) { View view = inflater.inflate(R.layout.item_table_header, parent, false); return new HeaderViewHolder(view); } else { View view = inflater.inflate(R.layout.item_table_row, parent, false); return new RowViewHolder(view); } } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { if (holder instanceof RowViewHolder) { Employee emp = employeeList.get(position - 1); // Skip header position RowViewHolder rowHolder = (RowViewHolder) holder; rowHolder.tvId.setText(String.valueOf(emp.getId())); rowHolder.tvName.setText(emp.getName()); rowHolder.tvDept.setText(emp.getDepartment()); } } @Override public int getItemCount() { return employeeList.size() + 1; // +1 for the header row } static class HeaderViewHolder extends RecyclerView.ViewHolder { public HeaderViewHolder(@NonNull View itemView) { super(itemView); } } static class RowViewHolder extends RecyclerView.ViewHolder { TextView tvId, tvName, tvDept; public RowViewHolder(@NonNull View itemView) { super(itemView); tvId = itemView.findViewById(R.id.tv_id); tvName = itemView.findViewById(R.id.tv_name); tvDept = itemView.findViewById(R.id.tv_dept); } } }
Set up the RecyclerView in your Activity layout (activity_main.xml):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_table" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
Initialize the RecyclerView in your Activity:
private void displayAsTable(List<Employee> employeeList) { RecyclerView recyclerView = findViewById(R.id.recycler_table); // 3 columns to match our 3 fields GridLayoutManager layoutManager = new GridLayoutManager(this, 3); recyclerView.setLayoutManager(layoutManager); EmployeeTableAdapter adapter = new EmployeeTableAdapter(employeeList); recyclerView.setAdapter(adapter); }
Finally, trigger the fetch process (e.g., in onCreate()):
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fetchJsonFromUrl("your_json_url_here"); }
- Add try-catch blocks around parsing logic to handle malformed JSON errors
- Adjust the model class and layout files to match your actual JSON structure and required fields
- For large datasets, consider adding pagination to keep the app responsive
内容的提问来源于stack exchange,提问作者Taylan Selvi

