MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON [英] MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path

查看:49
本文介绍了MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

到目前为止,我已经尝试使用以下链接中的答案来解决此问题: 1)MalformedJsonException with Retrofit API? 2)Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

以下是我的代码:

改装界面:

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

连接内容的维护活动:

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) {
            }
        });

    }
}

用户类:

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

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

}

服务器端期望JSON是这样的:

{
    "email" : "user.email",
    "verificationCode" : "123456"
}

我知道堆栈溢出中有一些常见问题,但都不能完全解决我的问题。

推荐答案

GsonBuilder gsonBuilder = new GsonBuilder();  
gsonBuilder.setLenient();  
Gson gson = gsonBuilder.create(); 

// and in you adapter set this instance
GsonConverterFactory.create(gson)

这篇关于MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆