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

时间:2018-03-16 07:55:32

标签: 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 $

到目前为止,我已尝试使用以下链接中的答案解决此问题: 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 with connection stuff:

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中有一些常见的问题,但它们都没有完全解决我的问题。

5 个答案:

答案 0 :(得分:2)

Set<Person> personOutputSet = 
    personList.stream()
              .filter(p -> p.getFirstName().contains(inputCriteriaFirstName))
              .collect(Collectors.toCollection(HashSet::new));

答案 1 :(得分:1)

发送数据时不会抛出异常,但是当gson尝试解析服务器响应时会抛出异常。根据您的代码,您希望服务器使用用户对象进行响应,但您还要发送用户对象。

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

进行改造的原因
  

{       “email”:“user.email”,       “verificationCode”:“123456”}

答案 2 :(得分:0)

确保标题正确。

对于我来说,我发送Accept-Encoding: gzip,因此服务器使用gzip返回该值。所以我将其删除,现在效果很好。

希望对您有帮助...

答案 3 :(得分:0)

删除“接受编码”标头。 OkHttp会为您处理gzip,但前提是您自己没有设置gzip。

答案 4 :(得分:0)

可能在您的元数据中,您必须正确地编写JSON文件。例如,如果是数组或两个对象,请确保不要错过方括号。

[
    { 
       "email" : "user.email", "verification" : "123456" 
    },
    { 
       "email" : "user.email", "verification" : "123456" 
    }
]