java - 反序列化时出现 Retrofit/Jackson 错误

标签 java android json jackson retrofit

我试图从我的网络服务获取 JSON 并反序列化到我的 UserSync 类,但出现以下错误:

无法从字符串值 ('') 实例化类型 [简单类型,类 com.example.breno.teste.model.User] 的值;没有单字符串构造函数/工厂方法 [来源:okhttp3.ResponseBody$BomAwareReader@fbf814f;行:1,列:86](通过引用链:com.example.breno.teste.dto.UserSync[“user”])

我读过一些帖子,说我需要在 UserSync 中声明我的 User 类静态,但是当我这样做时, jackson 找不到任何用户属性,即使使用 JsonDescription 也是如此。另一篇文章说我可能需要声明一个默认构造函数,所以我这样做了。

这是 UserSync 类:

@JsonIgnoreProperties(ignoreUnknown = true)
public class UserSync {
    @JsonProperty("status")
    private String Status;
    @JsonProperty("currentDate")
    private String CurrentDate;
    @JsonProperty("message")
    private String Message;
    @JsonProperty("user")
    private static User NewUser;

    public UserSync() {
    }

    public String getStatus() {
        return Status;
    }

    public String getCurrentDate() {
        return CurrentDate;
    }

    public String getMessage() {
        return Message;
    }

    public static User getNewUser() {
        return NewUser;
    }

用户类:

public class User implements Serializable {
    @JsonProperty("userKey")
    private UUID UserKey;
    @JsonProperty("userPassword")
    private String UserPassword;
    @JsonProperty("userGroupKey")
    private UUID UserGroupKey;
    @JsonProperty("signInDate")
    private String SignInDate;
    @JsonProperty("active")
    private boolean Active;
    @JsonProperty("profilePicturePath")
    private String ProfilePic;
    @JsonProperty("completeName")
    private String UserCompleteName;
    @JsonProperty("email")
    private String UserEmail;
    @JsonProperty("isLogged")
    private boolean IsLogged;

    public User() {
    }

    public boolean getIsLogged() {
        return IsLogged;
    }

    public void setIsLogged(boolean isLogged) {
        IsLogged = isLogged;
    }

    public String getUserEmail() {
        return UserEmail;
    }

    public void setUserEmail(String userEmail) {
        UserEmail = userEmail;
    }

    public UUID getUserKey() {
        return UserKey;
    }

    public void setUserKey(UUID userKey) {
        UserKey = userKey;
    }

    public String getUserPassword() {
        return UserPassword;
    }

    public void setUserPassword(String userPassword) {
        UserPassword = userPassword;
    }

    public UUID getUserGroupKey() {
        return UserGroupKey;
    }

    public void setUserGroupKey(UUID userGroupKey) {
        UserGroupKey = userGroupKey;
    }

    public String getSignInDate() {
        return SignInDate;
    }

    public void setSignInDate(String signInDate) {
        SignInDate = signInDate;
    }

    public boolean getActive() {
        return Active;
    }

    public void setActive(boolean active) {
        Active = active;
    }

    public String getProfilePic() {
        return ProfilePic;
    }

    public void setProfilePic(String profilePic) {
        ProfilePic = profilePic;
    }

    public String getUserCompleteName() {
        return UserCompleteName;
    }

    public void setUserCompleteName(String userCompleteName) {
        UserCompleteName = userCompleteName;
    }    
}

我的服务类(现在使用 postNewUser):

public interface UserService {
@GET("Login/LoginUser?")
Call<UserSync> login(@Query("email") String email, @Query("password") String password);

//region NewUser Services
@GET("Login/VerifyNewUser?")
Call<UserSync> validateNewUser(@Query("email") String email);

@POST("Login/PostNewUser")
Call<UserSync> postNewUser(@Body User user);
//endregion
}

最后是 JSON:

{
  "status": "OK",
  "currentDate": "20/07/2017 11:59:02",
  "message": "teste",
  "user": {
    "userKey": "8e2f0d2d-3522-472d-be1d-28791367f4ee",
    "email": "teste_teste@hotmail.com",
    "userPassword": "123456",
    "profilePicturePath": "teste",
    "completeName": "Jorge",
    "userGroupKey": null,
    "signInDate": "2017-07-07T16:26:06.097",
    "active": true,
    "isLogged": true
  }
}

有人可以帮我吗?

编辑 1 - 这是我用来进行改造调用的方法:

public void register(User user) {
        Call<UserSync> postCall = new RetrofitInitializator().getUserService().postNewUser(user);
        postCall.enqueue(getRegisterCallback());
    }

@NonNull
    private Callback<UserSync> getRegisterCallback() {
        return new Callback<UserSync>() {
            @Override
            public void onResponse(Call<UserSync> call, Response<UserSync> response) {
                User user = response.body().getNewUser();
            }
            @Override
            public void onFailure(Call<UserSync> call, Throwable t) {
                Log.e("Register - onFailure", t.getMessage());
            }
        };
    }

编辑 2 - RetrofitInicializator 类:

public class RetrofitInitializator {
    private final Retrofit retrofit;

    public RetrofitInitializator() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder builder = new OkHttpClient
                .Builder();
        builder.addInterceptor(interceptor);

        retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.15.6:7071/api/")
                .addConverterFactory(JacksonConverterFactory.create())
                .client(builder.build())
                .build();
    }

    public UserService getUserService() {
        return retrofit.create(UserService.class);
    }
}

最佳答案

我成功解决了将 User 类型切换为 JsonNode 并在此之后进行转换的问题。

@JsonProperty("status")
    private String Status;
    @JsonProperty("currentDate")
    private String CurrentDate;
    @JsonProperty("message")
    private String Message;
    @JsonProperty("user")
    private JsonNode NewUser;

和转换:

private User getUserFromUserAsync(UserSync userSync) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.treeToValue(userSync.getNewUser(), User.class);
    }

关于java - 反序列化时出现 Retrofit/Jackson 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45221728/

相关文章:

java - 未找到源 JAR 文件 mysql-connector-java-5.1.20-bin.jar 没有源附件

java - 在 Xcode 中编写 Java 程序

Android 网络服务发现不触发监听器

android - 如何以编程方式更改 android 工具栏中的图标?

java - GCJ 目前(2009 年年中)的现状如何?

java - 如何在 JMSMessage 中设置 JMS_IBM_MQMD_ACCOUNTINGTOKEN

android - 如何使俄语数量字符串正常工作?

javascript - 迭代并从 JSON 获取某些索引的唯一值

java - 如何将 JSONArray 放入 Android ListView 中

C#:如何在一个文件中读取 'éóú' 和 öäü 等字符?