MalformedJsonException:使用JsonReader.setLenient(true)在第1行第1列路径接受格式错误的JSON

abr*_*sze 5 android json gson retrofit retrofit2

尝试使用Retrofit以JSON格式发送信息,但它进入Retrofit的onFailure方法,并引发以下错误:

com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试通过使用以下链接的答案来解决此问题:1)带Retrofit API的MalformedJsonException? 2)使用JsonReader.setLenient(true)在第1行第1列路径$接受格式错误的JSON

这是我的代码:

改造界面:

public interface ServerApi {
    @POST("/register/test")
    Call<User> createAccount(@Body User user);
}
Run Code Online (Sandbox Code Playgroud)

MainActivity与连接的东西:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        User user= new User("myemail@mail.ru","vercode100");
        sendNetworkRequest(user);
    }

    private void sendNetworkRequest(User user){

        //create Retrofit instance
        Retrofit.Builder builder= new Retrofit.Builder()
                .baseUrl("http://localhost:8080")
                .addConverterFactory(GsonConverterFactory.create());

        Retrofit retrofit= builder.build();

        //Get client and call object for the request
        ServerApi client= retrofit.create(ServerApi.class);
        Call<User> call= client.createAccount(user);

        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
            }
        });

    }
}
Run Code Online (Sandbox Code Playgroud)

用户类别:

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

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

}
Run Code Online (Sandbox Code Playgroud)

服务器端希望这样的JSON:

{
    "email" : "user.email",
    "verificationCode" : "123456"
}
Run Code Online (Sandbox Code Playgroud)

我知道stackoverflow中存在一些常见问题,但是它们都不能完全解决我的问题。

Mar*_*ars 1

发送数据时不会引发异常,但当 gson 尝试解析服务器响应时会引发异常。根据您的代码,您期望服务器响应User对象,但您也发送了 User 对象。

您的服务器是否响应以下内容?因为这就是你所说的改造Call<User> createAccount(@Body User user)

{ "email" : "用户.email", "验证码" : "123456" }