【问题标题】:json data fetched from php and store them in an array in java从php获取的json数据并将它们存储在java中的数组中
【发布时间】:2025-12-18 22:40:01
【问题描述】:

我的 JSON 数组是这样的:

{"Name_1":1,"Name_2":0,"Name_3":0}

我在 java 中获取值并将它们存储在单独的数组中的代码如下:

int[] operations= new int[3];
             String result = "";
             InputStream is = null;
             StringBuilder sb=null;
                try{
                    HttpClient httpclient = new DefaultHttpClient();

                    HttpPost httppost = new HttpPost("http://testteamgr.netau.net/parsing/test.php");
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
            }catch(Exception e){
                    Log.e("log_tag", "Error in http connection "+e.toString());
            }
            //convert response to string
            try{
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                    sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                    }
                    is.close();

                    result=sb.toString();
            }catch(Exception e){
                    Log.e("log_tag", "Error converting result "+e.toString());
            }
            try{

                JSONObject json_data = new JSONObject(result);
                System.out.println("Length of json is"+jArray.length());
                for(int i=0;i<jArray.length();i++){

                       if (i==0) operations[0]=json_data.getInt("Name_1");
                       else if (i==1) operations[1]=json_data.getInt("Name_2");
                       else if (i==2) operations[2]=json_data.getInt("Name_3"); }

我收到了这些错误:

java.lang.string 类型的值 br 不能转换为 jsonobject

如果我打印出结果,我看不到 JSON 对象,而是看到 html 代码。

所以我想要的是将这 3 个值放入一个单独的数组中。

【问题讨论】:

  • 我认为这是因为你问了一个数组,而你只是得到了一个对象。在 JSON 中,数组被包裹在 [和] 之间,你有 { 和 },这意味着一个对象。
  • 代码已编辑但问题仍然存在
  • 哪个日志给你这个错误?
  • 代码如上。如果我添加结果的 println,在 result=sb.toString 之后我会看到 html 被打印出来。

标签: java php arrays json


【解决方案1】:

你有一个对象,而不是一个数组。要处理结果,您可以使用以下代码:

    String json = "{\"Name_1\":1,\"Name_2\":0,\"Name_3\":0}";
    JSONObject object = new JSONObject(json);
    String[] propertyNames = JSONObject.getNames(object);
    String[] values = new String[propertyNames.length];
    for (int i = 0; i < propertyNames.length; i++) {
        values[i] = String.valueOf(object.get(propertyNames[i]));
    }

【讨论】:

  • 如果字符串 json 不是静态的怎么办?如您所见,是我从 php 脚本中获取的代码。
  • 我只是用那个例子,尝试使用你获取的值,它应该可以工作。
最近更新 更多