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

Android中如何解析无数组名的JSON数组?

解析无外层数组名的JSON数组解决方案

你之前能顺利搞定带外层数组名的JSON解析,但这次服务器返回的是直接的JSON数组(没有外层键名),你的代码里踩了几个小坑,我帮你修正一下:

问题分析

  • 你把服务器返回的JSON数组字符串直接转换成了JSONObject,但返回的本身是JSONArray,这会直接抛出JSON解析异常
  • data和data2没有初始化,拼接时会带上null前缀,导致解析错误
  • 在AsyncTask的doInBackground里处理数据后,没有在主线程更新UI(Android规定子线程不能操作UI控件)
  • 读取输入流的逻辑有瑕疵,初始line赋值为空字符串会导致多拼接无效内容

修正后的完整代码

LineGraphSeries<DataPoint> series;
ArrayList<HashMap<String, String>> arrayListData;
public static String data = "", data2 = ""; // 初始化空字符串,避免null拼接问题
TextView graphOneTV, graphTwoTV, graphThreeTV;
GraphView graph;

public Graph_Fragment() { }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_graph_, container, false);
}

HttpURLConnection connection;

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    graphOneTV = view.findViewById(R.id.TVGraph1);
    graphTwoTV = view.findViewById(R.id.TVGraph2);
    graphThreeTV = view.findViewById(R.id.TVGraph3);
    graph = view.findViewById(R.id.graph1);
    
    graphDataClass gdc = new graphDataClass();
    gdc.execute();
}

public class graphDataClass extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... strings) {
        try {
            URL url = new URL("http://192.168.1.34/getGraphData.php");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = connection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            
            StringBuilder sb = new StringBuilder(); // 用StringBuilder优化字符串拼接效率
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            data = sb.toString();
            
            // 直接解析为JSONArray,因为服务器返回的就是纯数组格式
            JSONArray jsonArray = new JSONArray(data);
            data2 = ""; // 每次解析前清空,避免重复拼接旧数据
            for(int i=0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                int twitter = Integer.parseInt(jsonObject.optString("twitter"));
                int googleplus = Integer.parseInt(jsonObject.optString("googleplus"));
                data2 += "Node" + i + " : \n Twitter= " + twitter + " \n GooglePlus= " + googleplus + "\n";
            }
            
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return data2;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // 必须在主线程更新UI,onPostExecute是AsyncTask提供的主线程回调方法
        if(result != null && !result.isEmpty()) {
            graphOneTV.setText(result);
        } else {
            graphOneTV.setText("解析失败或无数据返回");
        }
    }
}

关键修改点说明

  • 初始化字符串变量:将data和data2初始化为空字符串,彻底避免拼接时出现nullxxx的无效内容
  • 直接解析JSONArray:服务器返回的是[{"twitter":"200",...},...]这种纯数组格式,所以直接用new JSONArray(data)创建数组对象,不需要先转JSONObject
  • 用StringBuilder优化拼接:循环里用+=拼接字符串会频繁创建新对象,StringBuilder能大幅提升效率
  • 在onPostExecute更新UI:严格遵循Android线程规则,把更新TextView的逻辑放到主线程执行的onPostExecute方法中
  • 修正流读取逻辑:去掉初始line的空字符串赋值,直接在while条件里读取内容,避免多拼接无效字符

这样修改后,就能正确解析服务器返回的无外层数组名的JSON数组,并把结果正常显示到TextView上了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:02:32