Hallo Zusammen
Ich habe ein Object, dass ich 1x als Json in eine Datei schreibe und 1x als DTO nutze. Nun verwende ich @SerializedName um die keys für das json file anders zu benennen. Beim DTO sollte @SerializedName ignoriert werden und der Name des Properties verwendet werden. Weiss jemand um Rat (ohne Reflection wenn möglich)?
Ich habe ein Object, dass ich 1x als Json in eine Datei schreibe und 1x als DTO nutze. Nun verwende ich @SerializedName um die keys für das json file anders zu benennen. Beim DTO sollte @SerializedName ignoriert werden und der Name des Properties verwendet werden. Weiss jemand um Rat (ohne Reflection wenn möglich)?
Java:
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class App {
public static void main(String[] args) {
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
Gson gson = builder.create();
Person person = new Person(1, "John", "Doe");
String json = gson.toJson(person);
System.out.println(json);
/*
Output 1 (output for json file):
{
"id": 1,
"forename": "John",
"surename": "Doe"
}
*/
Gson gson2 = new GsonBuilder().setExclusionStrategies(
new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(ExcludeField.class) != null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
).setPrettyPrinting().create();
String json2 = gson2.toJson(person); // toJson: how to ignore @SerializedName !
System.out.println(json2);
/*
Output 2 (dto, without id, ignore @SerializedName and use property name):
{
"firstname": "John",
"lastname": "Doe"
}
*/
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface ExcludeField {
}
class Person {
@ExcludeField
private int id;
@SerializedName("forename")
private String firstname;
@SerializedName("surename")
private String lastname;
public Person(int id, String firstname, String lastname) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
}
}