Skip to content

Commit 923029c

Browse files
authored
Merge pull request eugenp#6298 from soufiane-cheouati/master
Custom annotations files
2 parents 6bdf463 + 669dc78 commit 923029c

7 files changed

Lines changed: 208 additions & 0 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.baeldung.customannotations;
2+
3+
import static java.lang.annotation.ElementType.METHOD;
4+
import static java.lang.annotation.RetentionPolicy.RUNTIME;
5+
6+
import java.lang.annotation.Retention;
7+
import java.lang.annotation.Target;
8+
9+
@Retention(RUNTIME)
10+
@Target(METHOD)
11+
public @interface Init {
12+
13+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.baeldung.customannotations;
2+
3+
import static java.lang.annotation.ElementType.FIELD;
4+
import static java.lang.annotation.RetentionPolicy.RUNTIME;
5+
6+
import java.lang.annotation.Retention;
7+
import java.lang.annotation.Target;
8+
9+
@Retention(RUNTIME)
10+
@Target({ FIELD })
11+
public @interface JsonElement {
12+
public String key() default "";
13+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.baeldung.customannotations;
2+
3+
import static java.lang.annotation.ElementType.TYPE;
4+
import static java.lang.annotation.RetentionPolicy.RUNTIME;
5+
6+
import java.lang.annotation.Retention;
7+
import java.lang.annotation.Target;
8+
9+
@Retention(RUNTIME)
10+
@Target(TYPE)
11+
public @interface JsonSerializable {
12+
13+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.baeldung.customannotations;
2+
3+
public class JsonSerializationException extends RuntimeException {
4+
5+
private static final long serialVersionUID = 1L;
6+
7+
public JsonSerializationException(String message) {
8+
super(message);
9+
}
10+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.baeldung.customannotations;
2+
3+
import java.lang.reflect.Field;
4+
import java.lang.reflect.InvocationTargetException;
5+
import java.lang.reflect.Method;
6+
import java.util.HashMap;
7+
import java.util.Map;
8+
import java.util.Objects;
9+
import java.util.stream.Collectors;
10+
11+
public class ObjectToJsonConverter {
12+
public String convertToJson(Object object) throws JsonSerializationException {
13+
try {
14+
15+
checkIfSerializable(object);
16+
initializeObject(object);
17+
return getJsonString(object);
18+
19+
} catch (Exception e) {
20+
throw new JsonSerializationException(e.getMessage());
21+
}
22+
}
23+
24+
private void checkIfSerializable(Object object) {
25+
if (Objects.isNull(object)) {
26+
throw new JsonSerializationException("Can't serialize a null object");
27+
}
28+
29+
Class<?> clazz = object.getClass();
30+
if (!clazz.isAnnotationPresent(JsonSerializable.class)) {
31+
throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable");
32+
}
33+
}
34+
35+
private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
36+
Class<?> clazz = object.getClass();
37+
for (Method method : clazz.getDeclaredMethods()) {
38+
if (method.isAnnotationPresent(Init.class)) {
39+
method.setAccessible(true);
40+
method.invoke(object);
41+
}
42+
}
43+
}
44+
45+
private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException {
46+
Class<?> clazz = object.getClass();
47+
Map<String, String> jsonElementsMap = new HashMap<>();
48+
for (Field field : clazz.getDeclaredFields()) {
49+
field.setAccessible(true);
50+
if (field.isAnnotationPresent(JsonElement.class)) {
51+
jsonElementsMap.put(getKey(field), (String) field.get(object));
52+
}
53+
}
54+
55+
String jsonString = jsonElementsMap.entrySet()
56+
.stream()
57+
.map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"")
58+
.collect(Collectors.joining(","));
59+
return "{" + jsonString + "}";
60+
}
61+
62+
private String getKey(Field field) {
63+
String value = field.getAnnotation(JsonElement.class)
64+
.key();
65+
return value.isEmpty() ? field.getName() : value;
66+
}
67+
}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package com.baeldung.customannotations;
2+
3+
@JsonSerializable
4+
public class Person {
5+
@JsonElement
6+
private String firstName;
7+
@JsonElement
8+
private String lastName;
9+
@JsonElement(key = "personAge")
10+
private String age;
11+
12+
private String address;
13+
14+
public Person(String firstName, String lastName) {
15+
super();
16+
this.firstName = firstName;
17+
this.lastName = lastName;
18+
}
19+
20+
public Person(String firstName, String lastName, String age) {
21+
this.firstName = firstName;
22+
this.lastName = lastName;
23+
this.age = age;
24+
}
25+
26+
@Init
27+
private void initNames() {
28+
this.firstName = this.firstName.substring(0, 1)
29+
.toUpperCase() + this.firstName.substring(1);
30+
this.lastName = this.lastName.substring(0, 1)
31+
.toUpperCase() + this.lastName.substring(1);
32+
}
33+
34+
public String getFirstName() {
35+
return firstName;
36+
}
37+
38+
public void setFirstName(String firstName) {
39+
this.firstName = firstName;
40+
}
41+
42+
public String getLastName() {
43+
return lastName;
44+
}
45+
46+
public void setLastName(String lastName) {
47+
this.lastName = lastName;
48+
}
49+
50+
public String getAge() {
51+
return age;
52+
}
53+
54+
public void setAge(String age) {
55+
this.age = age;
56+
}
57+
58+
public String getAddress() {
59+
return address;
60+
}
61+
62+
public void setAddress(String address) {
63+
this.address = address;
64+
}
65+
66+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baeldung.customannotations;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
public class JsonSerializerUnitTest {
9+
10+
@Test
11+
public void givenObjectNotSerializedThenExceptionThrown() throws JsonSerializationException {
12+
Object object = new Object();
13+
ObjectToJsonConverter serializer = new ObjectToJsonConverter();
14+
assertThrows(JsonSerializationException.class, () -> {
15+
serializer.convertToJson(object);
16+
});
17+
}
18+
19+
@Test
20+
public void givenObjectSerializedThenTrueReturned() throws JsonSerializationException {
21+
Person person = new Person("soufiane", "cheouati", "34");
22+
ObjectToJsonConverter serializer = new ObjectToJsonConverter();
23+
String jsonString = serializer.convertToJson(person);
24+
assertEquals("{\"personAge\":\"34\",\"firstName\":\"Soufiane\",\"lastName\":\"Cheouati\"}", jsonString);
25+
}
26+
}

0 commit comments

Comments
 (0)