按下按钮后在Android中获取JSON响应错误

时间:2019-07-12 06:38:28

标签: android json

Image

您好,当尝试将JSON对象解析为字符串时,出现以下错误。

向服务器发送JSON对象时

Json请求:

{"name":"Building 1","level":1}

Json回复:

{"status":"success"}

下面是带有响应的已编辑代码。但是,服务器没有任何响应。

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(interceptor).build();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(API.URL_BASE)
    .client(client)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

API service = retrofit.create(API.class);
try {
    JSONObject parmobject=new JSONObject ();
    parmobject.put("name",name);
    parmobject.put("level",level);
    Call<NewBuilding> userCall = service.getbuildinglist (parmobject.toString ());
    userCall.enqueue(new Callback<NewBuilding> () {
        @Override
        public void onResponse(Call<NewBuilding> call, Response<NewBuilding> response) {
            if (response != null && response.code ()==200) {
                JSONObject obj = null;
                try {
                    obj = new JSONObject (String.valueOf (response));
                } catch (JSONException e) {
                    Log.e("My App", "Could not parse malformed JSON:");
                }

                String status = response.body ( ).getStatus ( ).toString ( );

                if(status.equalsIgnoreCase ("success")){
                    makeText(getActivity (), "Building successfully Added", Toast.LENGTH_SHORT).show();
                    arrayList.add (name);
                    adapter.notifyDataSetChanged ();
                }
            } else {
                makeText(getActivity (), "Please try again for Adding New Building", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<NewBuilding> call, Throwable t) {
            t.printStackTrace ();
        }
    });
} catch (JSONException e) {
    e.printStackTrace();
}

1 个答案:

答案 0 :(得分:0)

您可以添加拦截器以获取所得到的响应。

build.gradle

implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.5.0'

翻新

if (postService == null) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(interceptor).build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(base_url)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            postService = retrofit.create(PostService.class);

        }
        return postService;

然后您将在日志中看到详细信息,所有响应都将被看到。

作为回应

      @Override
      public void onResponse(Call<NewBuilding> call, Response <NewBuilding> response) {
      try {

        JSONObject obj = new JSONObject(response);
        Integer response1= obj.code();



      } catch (Throwable tx) {
        Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
      }
      }

Logcat:

  

W / System.err:com.google.gson.stream.MalformedJsonException:使用JsonReader.setLenient(true)在第1行第1列路径$接受格式错误的JSON $       W / System.err:位于com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1568)               在com.google.gson.stream.JsonReader.checkLenient(JsonReader.java:1409)               在com.google.gson.stream.JsonReader.doPeek(JsonReader.java:593)               在com.google.gson.stream.JsonReader.peek(JsonReader.java:425)       W / System.err:位于com.google.gson.internal.bind.ReflectiveTypeAdapterFactory $ Adapter.read(ReflectiveTypeAdapterFactory.java:205)               在retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:39)       W / System.err:位于retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27)               在retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:223)               在retrofit2.OkHttpCall $ 1.onResponse(OkHttpCall.java:121)               在okhttp3.RealCall $ AsyncCall.execute(RealCall.java:206)       W / System.err:位于okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)               在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)               在java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:587)               在java.lang.Thread.run(Thread.java:818)