Retrofit 2 OnFailure方法报MalformedJsonException错误求助
Hey there, let's tackle this MalformedJsonException you're facing when sending POST requests with images in Retrofit 2. The error "Expected value at line 2 column 1 path $" gives us a big clue—your JSON parser is trying to read from the start of the response, but the first line is empty (or has whitespace), and the actual JSON starts on line 2. Here's what to check and fix:
1. Verify Your Multipart Request Setup
First, since you're uploading an image, your Retrofit interface should use @Multipart correctly. If you're not using this annotation for image uploads, that's a common mistake. Here's how your interface should look:
@Multipart @POST("your-api-endpoint") Call<YourResponseModel> uploadWithImage( // Add your other text fields as RequestBody @Part("status") RequestBody status, // The image part with correct media type @Part MultipartBody.Part image );
When building the image request body, make sure you use the right media type for your image (e.g., image/jpeg, image/png):
File imageFile = new File("/path/to/your/image.jpg"); RequestBody imageRequestBody = RequestBody.create(MediaType.parse("image/jpeg"), imageFile); MultipartBody.Part imagePart = MultipartBody.Part.createFormData("image", imageFile.getName(), imageRequestBody);
2. Fix JSON Parsing for Whitespace-Prefixed Responses
The error points to line 2 being the start of valid JSON, which means your server is returning a blank line before the actual JSON response. This happens sometimes with multipart requests on certain server setups.
Quick Fix: Make Gson Lenient
If you're using GsonConverterFactory, you can configure Gson to ignore minor formatting issues like leading whitespace. Update your Retrofit instance setup:
Gson lenientGson = new GsonBuilder() .setLenient() // Allows Gson to skip leading whitespace/newlines .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(lenientGson)) .build();
Manual Workaround (If Server Can't Be Updated)
If you can't adjust the server's response, you can manually clean the response string before parsing. Change your interface to return Call<ResponseBody> instead of your model, then process it:
@Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccessful()) { try { // Trim all leading/trailing whitespace (including blank lines) String cleanResponse = response.body().string().trim(); // Parse the cleaned string into your model YourResponseModel model = new Gson().fromJson(cleanResponse, YourResponseModel.class); // Handle your success logic here } catch (IOException e) { e.printStackTrace(); } } else { // Handle error cases } }
3. Double-Check Server Response Consistency
Even though you shared a valid JSON response, confirm that the server returns exactly that JSON (no extra newlines or spaces) when handling multipart requests. Sometimes servers add debug logs or extra characters before the response body, which breaks JSON parsing.
内容的提问来源于stack exchange,提问作者Hitesh Kushwah

