You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Retrofit发送JSON请求触发MalformedJsonException问题求助

Hey, let's break down this issue step by step. That MalformedJsonException usually means one of two things: either the JSON your app is sending is invalid, or (more likely here) the server is returning something that's not valid JSON (like an HTML error page, plain text, or an empty response) when Retrofit tries to parse it into a User object.

First, Fix the Obvious Issues in Your Code

1. Update the User Class for Proper Gson Serialization/Deserialization

Gson needs a no-arg constructor to deserialize the server's response back into a User object, and while it can handle private fields, adding getters/setters makes things more reliable (especially if you use ProGuard later). Here's the adjusted class:

public class User {
    private String email;
    private String verificationCode;

    // Required for Gson to deserialize the server's response
    public User() {}

    public User(String email, String verificationCode) {
        this.email = email;
        this.verificationCode = verificationCode;
    }

    // Getters and Setters (optional but recommended)
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    public String getVerificationCode() { return verificationCode; }
    public void setVerificationCode(String verificationCode) { this.verificationCode = verificationCode; }
}

2. Fix the localhost Issue for Android Emulators

If you're testing with an Android emulator, localhost points to the emulator itself, not your computer's local server. Replace localhost with 10.0.2.2 (the special alias for your host machine's loopback interface):

Retrofit.Builder builder = new Retrofit.Builder()
        .baseUrl("http://10.0.2.2:8080") // Use this instead of localhost
        .addConverterFactory(GsonConverterFactory.create(lenientGson));

3. Configure Gson to Use Lenient Mode (Properly)

The solutions you tried might not have worked because you didn't explicitly pass a lenient Gson instance to Retrofit. Let's create one:

// Create a lenient Gson instance to handle minor JSON formatting issues
Gson lenientGson = new GsonBuilder()
        .setLenient()
        .create();

// Pass it to Retrofit's converter factory
Retrofit.Builder builder = new Retrofit.Builder()
        .baseUrl("http://10.0.2.2:8080")
        .addConverterFactory(GsonConverterFactory.create(lenientGson));

Next, Diagnose the Server's Response

The most common root cause here is that the server isn't returning valid JSON. Let's verify what it's sending back:

  1. Add Retrofit Logging: Use HttpLoggingInterceptor to log the full request and response. First add this dependency to your build.gradle:

    implementation 'com.squareup.okhttp3:logging-interceptor:4.11.0'
    

    Then add the interceptor to your Retrofit setup:

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(logging)
            .build();
    
    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://10.0.2.2:8080")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create(lenientGson));
    

    Check Logcat for the full response body—if it's HTML (like a 404 or 500 error page) or plain text, that's your problem.

  2. Test the API with Postman: Send the exact JSON your app should send ({"email":"myemail@mail.ru","verificationCode":"vercode100"}) to http://localhost:8080/register/test and see what the server returns. If it's not valid JSON, you'll need to fix the server-side code to return a proper JSON response (even for errors).

Additional Checks

  • Allow Cleartext Traffic: On Android 9+, HTTP requests are blocked by default. Add this to your AndroidManifest.xml inside the <application> tag:
    android:usesCleartextTraffic="true"
    
  • Verify Request Path: Ensure your @POST("/register/test") matches the server's actual endpoint path (no extra slashes or missing parts).

Final Notes

If after all this you still get the error, the issue is almost certainly with the server's response. Make sure it returns valid JSON for both success and error cases—even if the request fails, it should send back a JSON object with an error message instead of plain text or HTML.

内容的提问来源于stack exchange,提问作者abrutsze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:13:15