AndroidStudio请求一个服务器的信息,返回时,数据没有解析到TextView里显示

AndroidStudio请求一个服务器的信息,数据都返回了,但是在显示时却没有在TextView里面显示。
我这里是用的Handler接收的,用解析或转换成一个对象,这样的方式 解析的
下面是Handler代码

private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x02) {
                try {
                    JSONObject jsonObject = JSONObject.parseObject(msg.obj.toString());
                    //这里是要转换为一个对象,一个对象就是一个类,就是NewsResponseEntity
                    NewsResponseEntity entity = JSON.toJavaObject(jsonObject, NewsResponseEntity.class);
                    tv_news_show.append(entity.getContent() + "\n");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (msg.what == 0x01) {
                tv_news_show.setText(msg.obj.toString());
            }
        }
    };

下面是调试的代码

img

之前在Handler里面用的是tv_news_show.append(entity.getClass() + "\n");方式不行,又改为这个,直接显示内容,还是不行
下面是异常错误信息

W/System.err: com.alibaba.fastjson.JSONException: can not cast to JSONObject.
W/System.err:     at com.alibaba.fastjson.JSON.parseObject(JSON.java:262)
        at com.hnsaturn.tuxing003.ui.tuyue.AcNewsMusic$1.handleMessage(AcNewsMusic.java:78)

NewsResponseEntity实体类改为:

class NewsResponseEntity {
        int id;
        String title;
        String content;
        int type;
        String createTime;
        String updateTime;
    }

解析显示代码改为:

ArrayList<NewsResponseEntity> datas=   new Gson().fromJson(msg.obj.toString(),new TypeToken<ArrayList<NewsResponseEntity>>(){}.getType());
        tv_news_show.append(datas.get(0).getContent() + "\n");

img


这个错误信息告诉你了不能强转成JSONObject, 你这里是json数组,应该用JSONArray来解析外层,然后将数组里里面的对象都通过JSONObject解析出来


  private void getMSg(String result) {
        try {
            // 整个数组
            JSONArray jsonArray = new JSONArray(result);
            Log.d("TAG", "analyzeJSONArray1 jsonArray:" + jsonArray);

            for (int i = 0; i < jsonArray.length(); i++) {
                // JSON数组里面的具体-JSON对象
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String name = jsonObject.optString("name", null);
                int age = jsonObject.optInt("age", 0);
                String sex = jsonObject.optString("sex", null);

                // 日志打印结果:
                Log.d("sss", "analyzeJSONArray1 解析的结果:name" + name + " age:" + age + " sex:" + sex);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

img