java - 从php中获取json数据并将其存储在java中的数组中

标签 java php arrays json

我的 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"); }

我收到这些错误:

value br of type java.lang.string cannot be converted to jsonobject

如果我打印结果,我看不到 JSONobject,而是看到 html 代码。

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

最佳答案

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

    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]));
    }

关于java - 从php中获取json数据并将其存储在java中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11906499/

相关文章:

java - Android ExpandableListView getChildView 不触发

php - 如果数量列的数值小于或等于10,如何更改表格行的背景颜色

java - 如何将通用对象转换为原始数组?

php - 创建一个数组,然后将所有内容加在一起

java - JTDS 忽略 BigDecimal 上的 OpenJPA 比例注释

java - 将 javascript 与 java 混合

java - 如何在 spring RestController 中处理字符编码

javascript - 如何在我的网站服务器而不是我的电脑本地服务器上运行 node.js

javascript - jquery - php组合变量并输出结果

php - 手动将项目添加到现有对象 [Laravel 5]