You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android新手求助:解析服务器JSON数组并保存至Java变量

How to Parse JSON Array from PHP Server into Java Variables for Android

Hey there! Let's tackle this JSON parsing step by step—you're already halfway there with the HTTP connection working, so great job getting that far. Here's how to integrate JSON parsing into your existing code:

Step 1: Fix Your PHP Server Response

First, make sure your PHP script returns a valid JSON response with the right content type. This is critical for Java to parse it correctly:

  • Add this line at the top of your PHP file (before any output):
    header('Content-Type: application/json');
    
  • Instead of echoing "Data Matched", return a structured JSON object that includes your data array. For example:
    // Assume $dataArray is the array of results from your database
    $response = [
        "status" => "success",
        "data" => $dataArray,
        "message" => "Data fetched successfully"
    ];
    echo json_encode($response);
    exit;
    

If something goes wrong on the server, return an error JSON like:

$response = [
    "status" => "error",
    "message" => "No data found"
];
echo json_encode($response);
exit;

Step 2: Update Your HttpParse Class to Read Full Response

Your current postRequest method uses bufferedReader.readLine() which only reads one line of the response. JSON data might span multiple lines, so fix this to read the entire response:

if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
    String line;
    StringBuilder responseBuilder = new StringBuilder();
    // Read every line until end of stream
    while ((line = bufferedReader.readLine()) != null) {
        responseBuilder.append(line);
    }
    FinalHttpData = responseBuilder.toString();
} else {
    // Return a valid JSON error even if connection fails
    FinalHttpData = "{\"status\":\"error\",\"message\":\"Something Went Wrong\"}";
}

Step 3: Parse JSON in onPostExecute (Main Thread)

You were right to wonder where to put the parsing code—it belongs in onPostExecute because this method runs on the main thread, where you can update UI or start new activities. Here's how to modify your SGSearchFunction's onPostExecute:

First, create a simple model class to hold your data (replace fields with whatever your actual data needs):

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

// This class lets you store parsed data in a structured way
public class SGDataModel implements Serializable {
    private int id;
    private String name;
    private String details; // Example field—adjust to your data

    public SGDataModel(int id, String name, String details) {
        this.id = id;
        this.name = name;
        this.details = details;
    }

    // Getters to access the data later
    public int getId() { return id; }
    public String getName() { return name; }
    public String getDetails() { return details; }
}

Now update the onPostExecute method:

@Override
protected void onPostExecute(String httpResponseMsg) {
    super.onPostExecute(httpResponseMsg);
    progressDialog.dismiss();

    try {
        // Convert the response string to a JSONObject
        JSONObject responseObj = new JSONObject(httpResponseMsg);
        String status = responseObj.getString("status");

        if (status.equalsIgnoreCase("success")) {
            // Extract the JSON array from the response
            JSONArray dataArray = responseObj.getJSONArray("data");
            
            // Create a list to store your parsed data
            List<SGDataModel> sgDataList = new ArrayList<>();

            // Loop through the JSON array and parse each item
            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject itemObj = dataArray.getJSONObject(i);
                
                // Extract fields from the JSON object (match your PHP data keys!)
                int itemId = itemObj.getInt("id"); // Replace with your actual key
                String itemName = itemObj.getString("name"); // Replace with your actual key
                String itemDetails = itemObj.getString("details"); // Replace with your actual key

                // Add the parsed data to your list
                sgDataList.add(new SGDataModel(itemId, itemName, itemDetails));
            }

            // Pass the data to the next Activity
            Intent intent = new Intent(DashboardActivity.this, SGInfoActivity.class);
            intent.putExtra(SearchValue, SearchInput);
            // Since SGDataModel implements Serializable, we can pass the whole list
            intent.putExtra("sg_data_list", (Serializable) sgDataList);
            startActivity(intent);
            finish();
        } else {
            // Show error message from server
            String errorMsg = responseObj.getString("message");
            Toast.makeText(DashboardActivity.this, errorMsg, Toast.LENGTH_LONG).show();
        }
    } catch (JSONException e) {
        e.printStackTrace();
        Toast.makeText(DashboardActivity.this, "Failed to parse server data", Toast.LENGTH_LONG).show();
    }
}

Key Notes

  • Separate concerns: Keep HttpParse focused only on network requests—leave JSON parsing to your Activity's AsyncTask. This makes your code cleaner and easier to debug.
  • Handle exceptions: Always wrap JSON parsing in a try-catch block, since invalid JSON will throw a JSONException.
  • Match keys exactly: Make sure the keys you use in getString()/getInt() match the keys in your PHP JSON response (case-sensitive!).

内容的提问来源于stack exchange,提问作者rdimouro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:23:12