+-

尝试使用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("[email protected]","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中有一些常见的问题,但它们都没有完全解决我的问题.
最佳答案
发送数据时不会抛出异常,但是当gson尝试解析服务器响应时会抛出异常.根据您的代码,您希望服务器使用User对象进行响应,但您也要发送User对象.
您的服务器是否响应以下内容?因为这就是你用Call< User>进行改造的原因. createAccount(@Body用户用户)
{
“email” : “user.email”,
“verificationCode” : “123456” }
点击查看更多相关文章
转载注明原文:android – MalformedJsonException:使用JsonReader.setLenient(true)接受第1行第1列路径的格式错误的JSON - 乐贴网