像@jsonunwrapped一样的moshi序列化支持

时间:2018-03-01 09:50:14

标签: java spring-mvc jackson moshi

我有一个像这样的POJO:

class Registration {
    String name;

    @JsonUnwrapped
    ModifiableDetails detailsToModify;
}

class ModifiableDetails {
    String currentStatus;
    int enrollmentNumber;
}

当我使用内容

发出休息请求时
{ "name":"Lucy", "currentStatus":"active","enrollmentNumber":001}

Spring RestController将其反序列化为注册POJO,因为它使用Jackson进行反序列化。 在那之后,当我再次用Moshi适配器序列化对象时,我得到了这样的json:

{
 "name":"Lucy", 
 "detailsToModify":{
     "currentStatus":"active",
     "enrollmentNumber":001
  }
}

是否可以使用Moshi序列化对象,如:

{ "name":"Lucy", "currentStatus":"active","enrollmentNumber":001}

或者还有其他JsonAdapter(Jackson除外)可用于序列化对象吗?

提前致谢

1 个答案:

答案 0 :(得分:0)

最快的方法是使用中间类型的一次性JsonAdapter。

final class RegistrationJson {
  static final Object ADAPTER = new Object() {
    @FromJson Registration fromJson(RegistrationJson json) {
      return new Registration(json.name,
          new ModifiableDetails(json.currentStatus, json.enrollmentNumber));
    }

    @ToJson RegistrationJson toJson(Registration registration) {
      return new RegistrationJson(registration.name, registration.detailsToModify.currentStatus,
          registration.detailsToModify.enrollmentNumber);
    }
  };

  final String name;
  final String currentStatus;
  final int enrollmentNumber;

  RegistrationJson(String name, String currentStatus, int enrollmentNumber) {
    this.name = name;
    this.currentStatus = currentStatus;
    this.enrollmentNumber = enrollmentNumber;
  }
}

将其注册到您的Moshi实例,然后您可以执行以下操作。

Moshi moshi = new Moshi.Builder().add(RegistrationJson.ADAPTER).build();
JsonAdapter<Registration> adapter = moshi.adapter(Registration.class);
Registration registration = adapter.fromJson("{ \"name\":\"Lucy\", \"currentStatus\":\"active\",\"enrollmentNumber\":1}");
String json = adapter.toJson(registration);

请注意,001无效JSON。