【发布时间】:2018-08-25 05:15:46
【问题描述】:
尝试使用 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);
}
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) {
}
});
}
}
用户类别:
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"
}
我知道stackoverflow中有一些常见的问题,但都没有完全解决我的问题。
【问题讨论】:
标签: android json gson retrofit retrofit2