Issue
When serializing the object created by the builder of the message class with Gson, I want to get the key name android.
I think @Key should get android, not androidConfig, as a result of serialize, but It's not. The same goes for Objectmapper as well as Gson.
My development environment is Spring Boot 2.3.12.RELEASE, Firebase ADMIN SDK 8.0.1., Gson 2.8.8
[source]
message = Message.builder()
.setNotification(Notification.builder()
.setTitle(pushMessageDto.getTitle())
.setBody(pushMessageDto.getBody())
.setImage(pushMessageDto.getImage())
.build())
.setAndroidConfig(AndroidConfig.builder()
.setTtl(3600 * 1000)
.setNotification(AndroidNotification.builder()
.setIcon(ar.getIcon())
.setColor(ar.getColor())
.setClickAction(ar.getClickAction())
.build())
.build())
.setTopic(pushMessageDto.getTopic())
.build();
Gson gson = new Gson();
String m = gson.toJson(message);
[serializing results]
{
"validate_only":false,
"message":{
"notification":{
"title":"a",
"body":"b",
"image":"c"
},
"androidConfig":{
"ttl":"3",
"notification":{
"icon":"",
"color":"#32a852",
"clickAction":"MainActivity",
}
},
"topic":"weather"
}
}
[Message class of Firebase Admin SDK]
public class Message {
@Key("data")
private final Map<String, String> data;
@Key("notification")
private final Notification notification;
@Key("android")
private final AndroidConfig androidConfig;
@Key("webpush")
private final WebpushConfig webpushConfig;
@Key("apns")
private final ApnsConfig apnsConfig;
@Key("token")
private final String token;
@Key("topic")
private final String topic;
@Key("condition")
private final String condition;
@Key("fcm_options")
private final FcmOptions fcmOptions;
Solution
Gson by default only supports it's @SerializedName
annotation to specify custom JSON member names.
Assuming that the @Key
annotation you are using is available at runtime (@Retention(RUNTIME)
), you could write a custom FieldNamingStrategy
:
public class KeyFieldNamingStrategy implements FieldNamingStrategy {
private final FieldNamingStrategy delegate;
public KeyFieldNamingStrategy(FieldNamingStrategy delegate) {
this.delegate = delegate;
}
@Override
public String translateName(Field f) {
Key key = f.getAnnotation(Key.class);
if (key == null) {
// No annotation, use delegate
return delegate.translateName(f);
} else {
return key.value();
}
}
}
And then register it with a GsonBuilder
:
Gson gson = new GsonBuilder()
// Uses IDENTITY as delegate, which uses field names as is
.setFieldNamingStrategy(new KeyFieldNamingStrategy(FieldNamingPolicy.IDENTITY))
.create();
Answered By - Marcono1234 Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.