1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
import java.io.IOException; import java.lang.reflect.Field; import java.util.List;
@Component public class InternationalizedSerializer extends JsonSerializer<Result> {
@Autowired private LocalizationService localizationService;
private static final String FIELD_A = "a"; private static final String FIELD_B_LIST = "bList"; private static final String FIELD_NAME = "name"; private static final String FIELD_REAL_NAME = "realName";
@Override public void serialize(Result result, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject();
serializeA(result.getA(), gen);
serializeB(result.getBList(), result.getA(), gen);
gen.writeEndObject(); }
private void serializeA(List<MyDTO> aList, JsonGenerator gen) throws IOException { gen.writeArrayFieldStart(FIELD_A); for (MyDTO dto : aList) { gen.writeStartObject(); for (Field field : dto.getClass().getDeclaredFields()) { field.setAccessible(true); String fieldName = field.getName(); Object value; try { value = field.get(dto); } catch (IllegalAccessException e) { value = null; } gen.writeObjectField(fieldName, value); } gen.writeEndObject(); } gen.writeEndArray(); }
private void serializeB(List<B> bList, List<MyDTO> aList, JsonGenerator gen) throws IOException { gen.writeArrayFieldStart(FIELD_B_LIST); for (B b : bList) { gen.writeStartObject(); gen.writeStringField(FIELD_NAME, b.getName()); String locale = LocaleContextHolder.getLocale().toString(); String realName = getRealNameFromDTOs(aList, b.getName(), locale); gen.writeStringField(FIELD_REAL_NAME, realName); gen.writeEndObject(); } gen.writeEndArray(); }
private String getRealNameFromDTOs(List<MyDTO> dtos, String name, String locale) { for (MyDTO dto : dtos) { for (Field field : dto.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(InternationalizedField.class)) { InternationalizedField annotation = field.getAnnotation(InternationalizedField.class); if (annotation.key().equals(name)) { return localizationService.getLocalizedValue(annotation.key(), locale); } } } } return null; } }
|