jsonobject无法转换为jsonarray android studio

Posted

技术标签:

【中文标题】jsonobject无法转换为jsonarray android studio【英文标题】:jsonobject cannot be converted to jsonarray android studio 【发布时间】:2018-03-14 03:22:43 【问题描述】:

我想显示已经使用 JSON 上传到数据库 SQL 的图像

我已经为我的 android 和服务器端制作了这段代码

getImages.php

<?php 

//Importing dbdetails file 
require_once 'dbDetails.php';

//connection to database 
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');

//sql query to fetch all images 
$sql = "SELECT * FROM images";

//getting images 
$result = mysqli_query($con,$sql);

//response array 
$response = array(); 
$response['error'] = false; 
$response['images'] = array(); 

//traversing through all the rows 
while($row = mysqli_fetch_array($result))
    $temp = array(); 
    $temp['id']=$row['id'];
    $temp['name']=$row['name'];
    $temp['url']=$row['url'];
    array_push($response['images'],$temp);

//displaying the response 
echo json_encode($response);

然后对于 android 代码,我创建 MainActivity 类

public class MainActivity extends AppCompatActivity 

    //Web api url
    public static final String DATA_URL = "http://10.0.2.2/phpcode/getImages.php";

    //Tag values to read from json
    public static final String TAG_IMAGE_URL = "image";
    public static final String TAG_NAME = "name";

    //GridView Object
    private GridView gridView;

    //ArrayList for Storing image urls and titles
    private ArrayList<String> images;
    private ArrayList<String> names;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gridView = (GridView) findViewById(R.id.gridView);

        images = new ArrayList<>();
        names = new ArrayList<>();

        //Calling the getData method
        getData();
    

    private void getData()
        //Showing a progress dialog while our app fetches the data from url
        final ProgressDialog loading = ProgressDialog.show(this, "Please wait...","Fetching data...",false,false);

        //Creating a json array request to get the json from our api
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL,
                new Response.Listener<JSONArray>() 
                    @Override
                    public void onResponse(JSONArray response) 
                        //Dismissing the progressdialog on response
                        loading.dismiss();

                        //Displaying our grid
                        showGrid(response);
                    
                ,
                new Response.ErrorListener() 
                    @Override
                    public void onErrorResponse(VolleyError error) 
                        loading.dismiss();
                        Toast.makeText(getApplicationContext(), error.getMessage() + ".", Toast.LENGTH_LONG).show();
                    
                
        );

        //Creating a request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        //Adding our request to the queue
        requestQueue.add(jsonArrayRequest);
    


    private void showGrid(JSONArray jsonArray)
        //Looping through all the elements of json array
        for(int i = 0; i<jsonArray.length(); i++)
            //Creating a json object of the current index
            JSONObject obj = null;
            try 
                //getting json object from current index
                obj = jsonArray.getJSONObject(i);

                //getting image url and title from json object
                images.add(obj.getString(TAG_IMAGE_URL));
                names.add(obj.getString(TAG_NAME));
             catch (JSONException e) 
                e.printStackTrace();
            
        
        //Creating GridViewAdapter Object
        GridViewAdapter gridViewAdapter = new GridViewAdapter(this,images,names);

        //Adding adapter to gridview
        gridView.setAdapter(gridViewAdapter);
    


但结果是错误 JSONObject cannot be convert to JSONarray?

请帮我修复代码 我在工作中需要这段代码,我很困惑理解代码

================================ 这是我的gridView类

    public class GridViewAdapter extends BaseAdapter 

    //Imageloader to load images
    private ImageLoader imageLoader;

    //Context
    private Context context;

    //Array List that would contain the urls and the titles for the images
    private ArrayList<String> images;
    private ArrayList<String> names;

    public GridViewAdapter (Context context, ArrayList<String> images, ArrayList<String> names)
        //Getting all the values
        this.context = context;
        this.images = images;
        this.names = names;
    

    @Override
    public int getCount() 
        return images.size();
    

    @Override
    public Object getItem(int position) 
        return images.get(position);
    

    @Override
    public long getItemId(int position) 
        return 0;
    

    @Override
    public View getView(int position, View convertView, ViewGroup parent) 
        //Creating a linear layout
        LinearLayout linearLayout = new LinearLayout(context);
        linearLayout.setOrientation(LinearLayout.VERTICAL);

        //NetworkImageView
        NetworkImageView networkImageView = new NetworkImageView(context);

        //Initializing ImageLoader
        imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
        imageLoader.get(images.get(position), ImageLoader.getImageListener(networkImageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));

        //Setting the image url to load
        networkImageView.setImageUrl(images.get(position),imageLoader);

        //Creating a textview to show the title
        TextView textView = new TextView(context);
        textView.setText(names.get(position));

        //Scaling the imageview
        networkImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        networkImageView.setLayoutParams(new GridView.LayoutParams(200,200));

        //Adding views to the layout
        linearLayout.addView(textView);
        linearLayout.addView(networkImageView);

        //Returnint the layout
        return linearLayout;
    

================================================ = 安卓显示器

10-03 12:20:41.285 24381-24381/?我/艺术:没有后期启用 -Xcheck:jni(已经开启)10-03 12:20:41.285 24381-24381/? W/art:使用默认值的 X86 的意外 CPU 变体:x86 10-03 12:20:41.461 24381-24388/?我/艺术:调试器不再活动 10-03 12:20:41.461 24381-24388/? I/art:启动阻塞式 GC 仪器 10-03 12:20:41.543 24381-24381/? W/System: ClassLoader 引用未知 路径:/data/app/net.simplifiedcoding.androidcustomgridview-1/lib/x86 10-03 12:20:41.560 24381-24381/? I/InstantRun:开始即时运行 服务器:是主进程 10-03 12:20:41.935 24381-24410/? D/NetworkSecurityConfig:未指定网络安全配置,使用 平台默认

                                                      [ 10-03 12:20:41.965 24381:24405 D/         ]
                                                      HostConnection::get() New Host Connection established 0x9dfa0b80, tid

24405

                                                      [ 10-03 12:20:41.966 24381:24405 W/         ]
                                                      Unrecognized GLES max version string in extensions: ANDROID_EMU_CHECKSUM_HELPER_v1

ANDROID_EMU_dma_v1 10-03 12:20:41.983 24381-24405/? I/OpenGL渲染器: 初始化 EGL,版本 1.4 10-03 12:20:41.983 24381-24405/? D/OpenGLRenderer:交换行为 1 10-03 12:20:41.984 24381-24405/? W/OpenGLRenderer:无法选择配置 EGL_SWAP_BEHAVIOR_PRESERVED,重试不... 10-03 12:20:41.984 24381-24405/? D/OpenGLRenderer:交换行为 0 10-03 12:20:41.993 24381-24405/? D/EGL_emulation:eglCreateContext:0x9dffc920:maj 2 分钟 0 rcv 2 10-03 12:20:42.040 24381-24405/? D/EGL_仿真: eglMakeCurrent: 0x9dffc920: 版本 2 0 (tinfo 0x9df9f670) 10-03 12:20:42.403 24381-24405/? D/EGL_emulation: eglMakeCurrent: 0x9dfc920: 版本 2 0 (tinfo 0x9df9f670) 10-03 12:20:42.670 24381-24405/net.simplifiedcoding.androidcustomgridview D/EGL_emulation: eglMakeCurrent: 0x9dffc920: ver 2 0 (tinfo 0x9df9f670) 10-03 12:20:42.825 24381-24381/net.simplifiedcoding.androidcustomgridview W/art: 之前 Android 4.1,方法 int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) 会错误地覆盖包私有方法 在 android.widget.ListView 10-03 12:20:42.864 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err: org.json.JSONException:图像 10-03 12:20:42.865 没有值 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err: 在 org.json.JSONObject.get(JSONObject.java:389) 10-03 12:20:42.865 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err: 在 org.json.JSONObject.getString(JSONObject.java:550) 10-03 12:20:42.865 24381-24381/net.simplifiedcoding.androidcustomgridview W / System.err:在 net.simplifiedcoding.androidcustomgridview.MainActivity.showGrid(MainActivity.java:96) 10-03 12:20:42.865 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err: 在 net.simplifiedcoding.androidcustomgridview.MainActivity.access$000(MainActivity.java:22) 10-03 12:20:42.865 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err: 在 net.simplifiedcoding.androidcustomgridview.MainActivity$1.onResponse(MainActivity.java:66) 10-03 12:20:42.882 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err: 在 net.simplifiedcoding.androidcustomgridview.MainActivity$1.onResponse(MainActivity.java:58) 10-03 12:20:42.882 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err: 在 com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65) 10-03 12:20:42.882 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err: 在 com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99) 10-03 12:20:42.882 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err: 在 android.os.Handler.handleCallback(Handler.java:751) 10-03 12:20:42.882 24381-24381/net.simplifiedcoding.androidcustomgridview W / System.err:在 android.os.Handler.dispatchMessage(Handler.java:95) 10-03 12:20:42.882 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err: 在 android.os.Looper.loop(Looper.java:154) 10-03 12:20:42.882 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err: 在 android.app.ActivityThread.main(ActivityThread.java:6077) 10-03 12:20:42.882 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err:在 java.lang.reflect.Method.invoke(Native Method) 10-03 12:20:42.882 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err: 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 10-03 12:20:42.882 24381-24381/net.simplifiedcoding.androidcustomgridview W/System.err: 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

【问题讨论】:

你在哪一行得到这个错误? 应用程序已经安装到我的模拟器上,但是当我打开应用程序时,它说 org.json.JSONException: Value”error”;false,”images”;[“id”; org.json.JSONObeject 类型的 "1","name","agakpinggir","url","http",\/\/192.168.42.175\/AndroidImageUpload\/uploads\/1.jpg"] 不能转换为 JSONArray 【参考方案1】:

更改您的 getData 以接受 JSONObject。您正在从您的服务器传递 Jsonobject

 private void getData()
    //Showing a progress dialog while our app fetches the data from url
    final ProgressDialog loading = ProgressDialog.show(this, "Please wait...","Fetching data...",false,false);

    //Creating a json array request to get the json from our api
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.GET,DATA_URL,null,
            new Response.Listener<JSONObject>() 
                @Override
                public void onResponse(JSONObject response) 
                    //Dismissing the progressdialog on response
                    loading.dismiss();
                    try
                    //Displaying our grid
                    showGrid(response.getJSONArray("images");
                    catch(Exception e)
                
            ,
            new Response.ErrorListener() 
                @Override
                public void onErrorResponse(VolleyError error) 
                    loading.dismiss();
                    Toast.makeText(getApplicationContext(), error.getMessage() + ".", Toast.LENGTH_LONG).show();
                
            
    );

    //Creating a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    //Adding our request to the queue
    requestQueue.add(jsonObjectRequest);

【讨论】:

错误:未报告的异常 JSONException;必须被抓住或宣布被扔掉。这一行 showGrid(response.getJSONArray("images")); 在这条线上使用 try catch。我会更新我的代码。请检查 代码运行良好,但是应用打开时没有图片显示? 你是否在 GridView xml 中设置了 android:numColumns="2" 我设置了numColums="3",可以吗?【参考方案2】:

您没有从 PHP 返回 JSON 数组。要么直接回显json_encode($temp)而不将其推入数组,要么使用JSONObjectRequest而不是JSONArrayRequest并进行相应的解析。

【讨论】:

以上是关于jsonobject无法转换为jsonarray android studio的主要内容,如果未能解决你的问题,请参考以下文章

无法解析 JSONArray 无法转换为 JSONObject

org.json.JSONArray 无法转换为 JSONObject

值类型 org.json.JSONObject 无法转换为 JSONArray

org.json.JSONObject 类型的值无法转换为 JSONArray

org.json.JSONArray 类型的无法转换为 JSONObject

org.json.JSONException: org.json.JSONArray 类型的Value[] 无法转换为 JSONObject