如何从改造成功响应中转换json对象响应?

时间:2016-12-03 04:23:29

标签: android json gson retrofit

我使用过翻新文件上传。这里使用system.out.println我可以跟踪响应正文。但无法将响应转换为JSON对象。 我特此写下我的代码。请告诉我如何使用改造成功消息和失败消息解析并获取字符串值。

ApiConfig:

public interface ApiConfig {

    @Multipart
    @POST("general/Candidate/fileUpload")
    Call<ResponseBody> upload(
            @Header("Authorization") String authorization,
            @PartMap Map<String, RequestBody> map,
            @Part("id") RequestBody id,
            @Part("fileCount") RequestBody fileCount,
            @Part("fileType") RequestBody fileType,
            @Part("platform") RequestBody platform,
            @Part("externalID") RequestBody externalID);


}

ServiceGenerator:

public class ServiceGenerator {

    public static final String API_BASE_URL = "http://104.239.173.64/peoplecaddie-api/";

    private static Retrofit retrofit = null;
    private static OkHttpClient httpClient = new OkHttpClient.Builder()
            .readTimeout(60, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .build();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)

                    .addConverterFactory(GsonConverterFactory.create(new Gson()));

    public static <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = builder.client(httpClient).build();
        return retrofit.create(serviceClass);
    }

}

uploadFile1:

private void uploadFile1(Uri fileUri) {
    progressDialog.show();
    ApiConfig service =
            ServiceGenerator.createService(ApiConfig.class);



    File file = FileUtils.getFile(this, fileUri);
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), file);
    Map<String, RequestBody> map = new HashMap<>();
    map.put("fileContent0\"; filename=\"" + file.getName() + "\"", requestFile);
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("fileContent0", file.getName(), requestFile);
    String idStr = "1743";
    String fileCountStr = "1";
    String fileTypeStr = "SAMPLE";
    String platformStr = "Android";
    String externalIDStr = "portpolio";
    RequestBody idReq =
            RequestBody.create(
                    MediaType.parse("multipart/form-data"), idStr);
    RequestBody fileCountReq =
            RequestBody.create(
                    MediaType.parse("multipart/form-data"), fileCountStr);
    RequestBody fileTypeReq =
            RequestBody.create(
                    MediaType.parse("multipart/form-data"), fileTypeStr);
    RequestBody platformReq =
            RequestBody.create(
                    MediaType.parse("multipart/form-data"), platformStr);
    RequestBody externalIDReq =
            RequestBody.create(
                    MediaType.parse("multipart/form-data"), externalIDStr);
    // finally, execute the request
    Call<ResponseBody> call = service.upload("817b6ce98fd759e7f148b948246df6c1", map, idReq, fileCountReq, fileTypeReq, platformReq, externalIDReq);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call,
                               Response<ResponseBody> response) {
            try {
                System.out.println("Rrespppppp--->"+response.body().string());
                Log.e("response", "response------------------>" + response.body().string());
                JSONObject profileFileUploadResponse = new JSONObject(String.valueOf(response.body()));
                Log.e("retro", "retroFileResp------------------>" + profileFileUploadResponse);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.e("Upload error:", t.getMessage());
        }
    });

}

这里上传文件方法我可以使用跟踪响应。这很好。

 System.out.println("Rrespppppp--->"+response.body().string());

但是在尝试转换JSON对象时,它将无效,错误代码如下所示。请告诉我如何解析并使用此代码获取成功和失败响应值。

Log.e("response", "response------------------>" + response.body().string());
JSONObject profileFileUploadResponse = new JSONObject(String.valueOf(response.body()));
Log.e("retro", "retroFileResp------------------>" + profileFileUploadResponse);

先谢谢。

3 个答案:

答案 0 :(得分:0)

Retrofit Response已经采用json格式,您可以通过

获取项目
{ "result": [{ "fileId": 852, "status": 1, "pcData": { "id": 635, "filename": "IMG_20161122_175344.jpg", "filepath": "uploads\/peoplecaddie\/files\/1743_1480742360_IMG_20161122_‌​175344.jpg" } }] }


String fileid=response.body().getresult(0).getFileId();
String status=response.body().getresult(0).getStatus();

答案 1 :(得分:0)

修改了你的代码。请试试。您将在结果

中获得json对象
   Call<ResponseBody> call = service.upload("817b6ce98fd759e7f148b948246df6c1", map, idReq, fileCountReq, fileTypeReq, platformReq, externalIDReq);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call,
                                   Response<ResponseBody> response) {
                try {
                    System.out.println("Rrespppppp--->"+response.body().string());
                    Log.e("response", "response------------------>" + response.body().string());
                    //JSONObject profileFileUploadResponse = new JSONObject(String.valueOf(response.body()));
                    ResponseBody result = response.body();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("Upload error:", t.getMessage());
            }
        });

答案 2 :(得分:0)

尝试一下,它将起作用

将呼叫类型更改为 JsonElement

@GET("LoginAPI")
Call<JsonElement> getLogin(@Query("Username") String userName,
                           @Query("Password") String password);

从响应中获取Json对象

public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
    try {
        JSONObject object = new JSONObject(response.body().toString());
        textView.setText(object.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        textView.setText(e.getMessage());
    }
}