Java 11497 (#12399)

* Added/created parent module (json-modules)

* moved json(submodule) to json-modules(parent)

* moved json-2(submodule) to json-modules(parent)

* moved json-path(submodule) to json-modules(parent)

* moved gson(submodule) to json-modules(parent)

* deleted sub-modules that we moved to json-modules

Co-authored-by: panagiotiskakos <panagiotis.kakos@libra-is.com>
This commit is contained in:
panos-kakos
2022-06-24 17:28:34 +01:00
committed by GitHub
parent b792ab1932
commit a51caf51f3
163 changed files with 377 additions and 336 deletions
@@ -0,0 +1,95 @@
package com.baeldung.fastjson;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.BeanContext;
import com.alibaba.fastjson.serializer.ContextValueFilter;
import com.alibaba.fastjson.serializer.NameFilter;
import com.alibaba.fastjson.serializer.SerializeConfig;
import org.junit.Before;
import org.junit.Test;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class FastJsonUnitTest {
private List<Person> listOfPersons;
@Before
public void setUp() {
listOfPersons = new ArrayList<Person>();
Calendar calendar = Calendar.getInstance();
calendar.set(2016, 6, 24);
listOfPersons.add(new Person(15, "John", "Doe", calendar.getTime()));
listOfPersons.add(new Person(20, "Janette", "Doe", calendar.getTime()));
}
@Test
public void whenJavaList_thanConvertToJsonCorrect() {
String personJsonFormat = JSON.toJSONString(listOfPersons);
assertEquals(personJsonFormat, "[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":" + "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":" + "\"24/07/2016\"}]");
}
@Test
public void whenJson_thanConvertToObjectCorrect() {
String personJsonFormat = JSON.toJSONString(listOfPersons.get(0));
Person newPerson = JSON.parseObject(personJsonFormat, Person.class);
assertEquals(newPerson.getAge(), 0); // serialize is set to false for age attribute
assertEquals(newPerson.getFirstName(), listOfPersons.get(0)
.getFirstName());
assertEquals(newPerson.getLastName(), listOfPersons.get(0)
.getLastName());
}
@Test
public void whenGenerateJson_thanGenerationCorrect() throws ParseException {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 2; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("FIRST NAME", "John" + i);
jsonObject.put("LAST NAME", "Doe" + i);
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
jsonArray.add(jsonObject);
}
assertEquals(jsonArray.toString(), "[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":" + "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\"," + "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]");
}
@Test
public void givenContextFilter_whenJavaObject_thanJsonCorrect() {
ContextValueFilter valueFilter = new ContextValueFilter() {
public Object process(BeanContext context, Object object, String name, Object value) {
if (name.equals("DATE OF BIRTH")) {
return "NOT TO DISCLOSE";
}
if (value.equals("John") || value.equals("Doe")) {
return ((String) value).toUpperCase();
} else {
return null;
}
}
};
JSON.toJSONString(listOfPersons, valueFilter);
}
@Test
public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() {
NameFilter formatName = new NameFilter() {
public String process(Object object, String name, Object value) {
return name.toLowerCase()
.replace(" ", "_");
}
};
SerializeConfig.getGlobalInstance()
.addFilter(Person.class, formatName);
String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, "yyyy-MM-dd");
assertEquals(jsonOutput, "[{\"first_name\":\"Doe\",\"last_name\":\"John\"," + "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":" + "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]");
// resetting custom serializer
SerializeConfig.getGlobalInstance()
.put(Person.class, null);
}
}
@@ -0,0 +1,69 @@
package com.baeldung.fastjson;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Date;
public class Person {
@JSONField(name = "AGE", serialize = false, deserialize = false)
private int age;
@JSONField(name = "LAST NAME", ordinal = 2)
private String lastName;
@JSONField(name = "FIRST NAME", ordinal = 1)
private String firstName;
@JSONField(name = "DATE OF BIRTH", format = "dd/MM/yyyy", ordinal = 3)
private Date dateOfBirth;
public Person() {
}
public Person(int age, String lastName, String firstName, Date dateOfBirth) {
super();
this.age = age;
this.lastName = lastName;
this.firstName = firstName;
this.dateOfBirth = dateOfBirth;
}
@Override
public String toString() {
return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" + firstName + ", dateOfBirth=" + dateOfBirth + "]";
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
@@ -0,0 +1,85 @@
package com.baeldung.jsoniter;
import com.baeldung.jsoniter.model.Name;
import com.baeldung.jsoniter.model.Student;
import com.jsoniter.JsonIterator;
import com.jsoniter.ValueType;
import com.jsoniter.any.Any;
import org.junit.Test;
import static com.jsoniter.ValueType.STRING;
import static org.assertj.core.api.Assertions.assertThat;
public class JsoniterIntroUnitTest {
@Test
public void whenParsedUsingBindAPI_thenConvertedToJavaObjectCorrectly() {
String input = "{\"id\":1,\"name\":{\"firstName\":\"Joe\",\"surname\":\"Blogg\"}}";
Student student = JsonIterator.deserialize(input, Student.class);
assertThat(student.getId()).isEqualTo(1);
assertThat(student.getName().getFirstName()).isEqualTo("Joe");
assertThat(student.getName().getSurname()).isEqualTo("Blogg");
}
@Test
public void givenTypeInJsonFuzzy_whenFieldIsMaybeDecoded_thenFieldParsedCorrectly() {
String input = "{\"id\":\"1\",\"name\":{\"firstName\":\"Joe\",\"surname\":\"Blogg\"}}";
Student student = JsonIterator.deserialize(input, Student.class);
assertThat(student.getId()).isEqualTo(1);
}
@Test
public void whenParsedUsingAnyAPI_thenFieldValueCanBeExtractedUsingTheFieldName() {
String input = "{\"id\":1,\"name\":{\"firstName\":\"Joe\",\"surname\":\"Blogg\"}}";
Any any = JsonIterator.deserialize(input);
assertThat(any.toInt("id")).isEqualTo(1);
assertThat(any.toString("name", "firstName")).isEqualTo("Joe");
assertThat(any.toString("name", "surname")).isEqualTo("Blogg");
}
@Test
public void whenParsedUsingAnyAPI_thenFieldValueTypeIsCorrect() {
String input = "{\"id\":1,\"name\":{\"firstName\":\"Joe\",\"surname\":\"Blogg\"}}";
Any any = JsonIterator.deserialize(input);
assertThat(any.get("id").valueType()).isEqualTo(ValueType.NUMBER);
assertThat(any.get("name").valueType()).isEqualTo(ValueType.OBJECT);
assertThat(any.get("error").valueType()).isEqualTo(ValueType.INVALID);
}
@Test
public void whenParsedUsingIteratorAPI_thenFieldValuesExtractedCorrectly() throws Exception {
Name name = new Name();
String input = "{ \"firstName\" : \"Joe\", \"surname\" : \"Blogg\" }";
JsonIterator iterator = JsonIterator.parse(input);
for (String field = iterator.readObject(); field != null; field = iterator.readObject()) {
switch (field) {
case "firstName":
if (iterator.whatIsNext() == ValueType.STRING) {
name.setFirstName(iterator.readString());
}
continue;
case "surname":
if (iterator.whatIsNext() == ValueType.STRING) {
name.setSurname(iterator.readString());
}
continue;
default:
iterator.skip();
}
}
assertThat(name.getFirstName()).isEqualTo("Joe");
assertThat(name.getSurname()).isEqualTo("Blogg");
}
}
@@ -0,0 +1,51 @@
package com.baeldung.jsonld.deserialization.jsonldjava.jackson;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.HashMap;
import org.junit.jupiter.api.Test;
import com.baeldung.jsonld.deserialization.jsonldjava.jackson.Person.Link;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.jsonldjava.core.JsonLdOptions;
import com.github.jsonldjava.core.JsonLdProcessor;
import com.github.jsonldjava.utils.JsonUtils;
public class JacksonDeserializationUnitTest {
@Test
void givenAJsonLdObject_whenCompactIsUsedWithEmptyContext_thenItCanBeDeserializedWithJackson() throws IOException {
String inputJsonLd = "{"
+ "\"@context\":{"
+ "\"@vocab\":\"http://schema.org/\","
+ "\"knows\":{\"@type\":\"@id\"}"
+ "},"
+ "\"@type\":\"Person\","
+ "\"@id\":\"http://example.com/person/1234\","
+ "\"name\":\"Example Name\","
+ "\"knows\":\"http://example.com/person/2345\""
+ "}";
Object jsonObject = JsonUtils.fromString(inputJsonLd);
Object compact = JsonLdProcessor.compact(jsonObject, new HashMap<>(), new JsonLdOptions());
String compactContent = JsonUtils.toString(compact);
assertEquals("{"
+ "\"@id\":\"http://example.com/person/1234\","
+ "\"@type\":\"http://schema.org/Person\","
+ "\"http://schema.org/knows\":{\"@id\":\"http://example.com/person/2345\"},"
+ "\"http://schema.org/name\":\"Example Name\""
+ "}", compactContent);
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(compactContent, Person.class);
Person expectedPerson = new Person("http://example.com/person/1234", "Example Name", new Link("http://example.com/person/2345"));
assertEquals(expectedPerson.getId(), person.getId());
assertEquals(expectedPerson.getName(), person.getName());
assertEquals(expectedPerson.getKnows().getId(), person.getKnows().getId());
}
}
@@ -0,0 +1,67 @@
package com.baeldung.jsonld.deserialization.jsonldjava.jackson;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
@JsonProperty("@id")
private String id;
@JsonProperty("http://schema.org/name")
private String name;
@JsonProperty("http://schema.org/knows")
private Link knows;
public Person() {
}
public Person(String id, String name, Link knows) {
this.id = id;
this.name = name;
this.knows = knows;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Link getKnows() {
return knows;
}
public void setKnows(Link knows) {
this.knows = knows;
}
public static class Link {
@JsonProperty("@id")
private String id;
public Link() {
}
public Link(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
}
@@ -0,0 +1,63 @@
package com.baeldung.jsonld.serialization.hydrajsonld;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase;
import de.escalon.hypermedia.hydra.serialize.JacksonHydraSerializer;
public class HydraJsonldSerializationUnitTest {
@Test
void givenAHydraJsonldAnnotatedObject_whenJacksonHydraSerializerIsUsed_thenAJsonLdDocumentIsGenerated() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(getJacksonHydraSerializerModule());
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
Person person = new Person("http://example.com/person/1234", "Example Name");
String personJsonLd = objectMapper.writeValueAsString(person);
assertEquals("{"
+ "\"@context\":{"
+ "\"@vocab\":\"http://example.com/vocab/\","
+ "\"name\":\"fullName\""
+ "},"
+ "\"@type\":\"person\","
+ "\"name\":\"Example Name\","
+ "\"@id\":\"http://example.com/person/1234\""
+ "}", personJsonLd);
}
static SimpleModule getJacksonHydraSerializerModule() {
return new SimpleModule() {
@Override
public void setupModule(SetupContext context) {
super.setupModule(context);
context.addBeanSerializerModifier(new BeanSerializerModifier() {
@Override
public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
if (serializer instanceof BeanSerializerBase) {
return new JacksonHydraSerializer((BeanSerializerBase) serializer);
} else {
return serializer;
}
}
});
}
};
}
}
@@ -0,0 +1,28 @@
package com.baeldung.jsonld.serialization.hydrajsonld;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.escalon.hypermedia.hydra.mapping.Expose;
import de.escalon.hypermedia.hydra.mapping.Vocab;
@Vocab("http://example.com/vocab/")
@Expose("person")
public class Person {
private String id;
private String name;
public Person(String id, String name) {
this.id = id;
this.name = name;
}
@JsonProperty("@id")
public String getId() {
return id;
}
@Expose("fullName")
public String getName() {
return name;
}
}
@@ -0,0 +1,33 @@
package com.baeldung.jsonld.serialization.jacksonjsonld;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ioinformarics.oss.jackson.module.jsonld.JsonldModule;
public class JacksonJsonLdSerializationUnitTest {
@Test
void givenAJacksonJsonldAnnotatedObject_whenJsonldModuleIsUsed_thenAJsonLdDocumentIsGenerated() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JsonldModule());
Person person = new Person("http://example.com/person/1234", "Example Name");
String personJsonLd = objectMapper.writeValueAsString(person);
assertEquals("{"
+ "\"@type\":\"s:Person\","
+ "\"@context\":{"
+ "\"s\":\"http://schema.org/\","
+ "\"name\":\"s:name\","
+ "\"knows\":{\"@id\":\"s:knows\",\"@type\":\"@id\"}"
+ "},"
+ "\"name\":\"Example Name\","
+ "\"@id\":\"http://example.com/person/1234\","
+ "\"knows\":\"http://example.com/person/2345\""
+ "}", personJsonLd);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.jsonld.serialization.jacksonjsonld;
import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldId;
import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldLink;
import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldNamespace;
import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldProperty;
import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldResource;
import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldType;
@JsonldResource
@JsonldNamespace(name = "s", uri = "http://schema.org/")
@JsonldType("s:Person")
@JsonldLink(rel = "s:knows", name = "knows", href = "http://example.com/person/2345")
public class Person {
@JsonldId
private String id;
@JsonldProperty("s:name")
private String name;
public Person(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
@@ -0,0 +1,180 @@
package com.baeldung.jsonoptimization;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.zip.GZIPOutputStream;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.module.SimpleModule;
class JsonOptimizationUnitTest {
private static final String TEST_LABEL_JACKSON_DEFAULT_OPTIONS = "Default JSON";
private static final String TEST_LABEL_DEFAULT_JSON_NO_NULL = "Default JSON without null";
private static final String TEST_LABEL_SHORTER_FIELD_NAMES = "Shorter field names";
private static final String TEST_LABEL_SHORTER_FIELD_NAMES_AND_NO_NULL = "Shorter field names without null";
private static final String TEST_LABEL_SERIALIZING_TO_ARRAY = "Custom serializer";
private static final String TEST_LABEL_SLIM_CUSTOM_SERIALIZER = "Slim custom serializer";
private static final String TEST_LABEL_SLIM_CUSTOMER = "Slim customer";
private static final String TEST_LABEL_SLIM_CUSTOMER_SHORT_NAMES = "Slim customer with shorter field names";
private static DecimalFormat LENGTH_FORMATTER = new DecimalFormat("###,###.0");
private static DecimalFormat PERCENT_FORMATTER = new DecimalFormat("###.0");
private static Customer[] customers;
private ObjectMapper mapper;
private static int defaultJsonLength;
@BeforeAll
static void setUpOnce() throws Exception {
customers = Customer.fromMockFile();
ObjectMapper oneTimeMapper = new ObjectMapper();
byte[] feedback = oneTimeMapper.writeValueAsBytes(customers);
defaultJsonLength = feedback.length;
System.out.println();
System.out.println("Default JSON length: " + defaultJsonLength);
System.out.println();
}
@BeforeEach
void setUp() {
mapper = new ObjectMapper();
}
@Test
void whenSetUp_ThenOneThousandCustomers() {
assertEquals(1000, customers.length, "There should be a 1000 customers");
}
@Test
void whenJacksonDefaultOptions_thenValid() throws IOException {
printBanner(TEST_LABEL_JACKSON_DEFAULT_OPTIONS);
byte[] plainJson = createJsonAndVerify(TEST_LABEL_JACKSON_DEFAULT_OPTIONS, customers);
compressJson(TEST_LABEL_JACKSON_DEFAULT_OPTIONS, plainJson);
}
@Test
void whenExcludingNull_thenValid() throws IOException {
printBanner(TEST_LABEL_DEFAULT_JSON_NO_NULL);
mapper.setSerializationInclusion(Include.NON_NULL);
byte[] plainJson = createJsonAndVerify(TEST_LABEL_DEFAULT_JSON_NO_NULL, customers);
compressJson(TEST_LABEL_DEFAULT_JSON_NO_NULL, plainJson);
}
@Test
void whenShorterFieldNames_thenValid() throws IOException {
printBanner(TEST_LABEL_SHORTER_FIELD_NAMES);
CustomerShortNames[] shorterOnes = CustomerShortNames.fromCustomers(customers);
byte[] shorterJson = createJsonAndVerify(TEST_LABEL_SHORTER_FIELD_NAMES, shorterOnes);
compressJson(TEST_LABEL_SHORTER_FIELD_NAMES, shorterJson);
}
@Test
void whenShorterFieldNamesAndExcludingNull_thenValid() throws IOException {
printBanner(TEST_LABEL_SHORTER_FIELD_NAMES_AND_NO_NULL);
CustomerShortNames[] shorterOnes = CustomerShortNames.fromCustomers(customers);
mapper.setSerializationInclusion(Include.NON_NULL);
byte[] shorterJson = createJsonAndVerify(TEST_LABEL_SHORTER_FIELD_NAMES_AND_NO_NULL, shorterOnes);
compressJson(TEST_LABEL_SHORTER_FIELD_NAMES_AND_NO_NULL, shorterJson);
}
@Test
void whenSlimCustomer_thenValid() throws IOException {
printBanner(TEST_LABEL_SLIM_CUSTOMER);
CustomerSlim[] slimOnes = CustomerSlim.fromCustomers(customers);
byte[] slimJson = createJsonAndVerify(TEST_LABEL_SLIM_CUSTOMER, slimOnes);
compressJson(TEST_LABEL_SLIM_CUSTOMER, slimJson);
}
@Test
void whenSlimCustomerAndShorterFieldNames_thenValid() throws IOException {
printBanner(TEST_LABEL_SLIM_CUSTOMER_SHORT_NAMES);
CustomerSlimShortNames[] slimOnes = CustomerSlimShortNames.fromCustomers(customers);
byte[] slimJson = createJsonAndVerify(TEST_LABEL_SLIM_CUSTOMER_SHORT_NAMES, slimOnes);
compressJson(TEST_LABEL_SLIM_CUSTOMER_SHORT_NAMES, slimJson);
}
@Test
void whenSerializingToArray_thenValid() throws IOException {
printBanner(TEST_LABEL_SERIALIZING_TO_ARRAY);
SimpleModule serializer = new SimpleModule("CustomDeSerializer", new Version(1, 0, 0, null, null, null));
serializer.addSerializer(Customer.class, new CustomerSerializer());
serializer.addDeserializer(Customer.class, new CustomerDeserializer());
mapper.registerModule(serializer);
byte[] plainJson = createJsonAndVerify(TEST_LABEL_SERIALIZING_TO_ARRAY, customers);
compressJson(TEST_LABEL_SERIALIZING_TO_ARRAY, plainJson);
}
@Test
void whenSerializingToArrayAndSlimCustomer_thenValid() throws IOException {
printBanner(TEST_LABEL_SLIM_CUSTOM_SERIALIZER);
SimpleModule serializer = new SimpleModule("SlimCustomDeSerializer", new Version(1, 0, 0, null, null, null));
serializer.addSerializer(CustomerSlim.class, new CustomerSlimSerializer());
serializer.addDeserializer(CustomerSlim.class, new CustomerSlimDeserializer());
mapper.registerModule(serializer);
CustomerSlim[] slimOnes = CustomerSlim.fromCustomers(customers);
byte[] plainJson = createJsonAndVerify(TEST_LABEL_SLIM_CUSTOM_SERIALIZER, slimOnes);
compressJson(TEST_LABEL_SLIM_CUSTOM_SERIALIZER, plainJson);
}
private void printBanner(String name) {
System.out.println();
System.out.println("************************************************");
System.out.println("Testing " + name);
System.out.println();
}
void compressJson(String label, byte[] plainJson) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzipStream = new GZIPOutputStream(outputStream);
gzipStream.write(plainJson);
gzipStream.close();
outputStream.close();
byte[] gzippedJson = outputStream.toByteArray();
double length = gzippedJson.length / 1024d;
double percent = gzippedJson.length * 100d / defaultJsonLength;
System.out.println(label + " GZIPped length: " + LENGTH_FORMATTER.format(length)
+ "kB (" + PERCENT_FORMATTER.format(percent) + "%)");
assertTrue(plainJson.length > gzippedJson.length, label + " should be longer than GZIPped data");
}
private byte[] createJsonAndVerify(String label, Object[] customers) throws IOException {
System.out.println(label + " sample: ");
ObjectWriter prettyWritter = mapper.writerWithDefaultPrettyPrinter();
System.out.println(prettyWritter.writeValueAsString(customers[0]));
byte[] feedback = mapper.writeValueAsBytes(customers);
double length = feedback.length / 1024d;
double percent = feedback.length * 100d / defaultJsonLength;
System.out.println(label + " length: " + LENGTH_FORMATTER.format(length)
+ "kB (" + PERCENT_FORMATTER.format(percent) + "%)");
assertTrue(feedback.length > 1, label + " should be there");
String prefix = label.replaceAll(" ", "-")
.toLowerCase();
File tempFile = File.createTempFile("jon-optimization-" + prefix, ".json");
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(feedback);
fos.close();
System.out.println(label + " file: " + tempFile.toString());
Object[] restoredOnes = mapper.readValue(feedback, customers.getClass());
assertArrayEquals(TEST_LABEL_JACKSON_DEFAULT_OPTIONS + ": restoring from JSON should work", customers, restoredOnes);
return feedback;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.jsontojavaclass;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class JsonToJavaClassConversionUnitTest {
private JsonToJavaClassConversion jsonToJavaConversion = new JsonToJavaClassConversion();
@Test
void whenProvideInputJSON_thenGenerateJavaClass() throws MalformedURLException, IOException {
String packageName = "com.baeldung.jsontojavaclass.pojo";
// load input JSON file
String jsonPath = "src/test/resources/";
File inputJson = new File(jsonPath + "sample_input.json");
// create the local directory for generating the Java Class file
String outputPath = "src/test/resources/";
File outputJavaClassDirectory = new File(outputPath);
String javaClassName = "SamplePojo";
jsonToJavaConversion.convertJsonToJavaClass(inputJson.toURI()
.toURL(), outputJavaClassDirectory, packageName, javaClassName);
File outputJavaClassPath = new File(outputPath + packageName.replace(".", "/"));
Assertions.assertTrue(Arrays.stream(outputJavaClassPath.listFiles()).peek(System.out::println).anyMatch(file -> (javaClassName+".java").equalsIgnoreCase(file.getName())));
}
}
@@ -0,0 +1,35 @@
package com.baeldung.jsonvalidation;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class GsonValidatorUnitTest {
private final GsonValidator validator = new GsonValidator();
@Test
public void givenValidObjectJson_whenValidatingNonStrict_thenValid() {
String json = "{\"email\": \"example@com\", \"name\": \"John\"}";
assertTrue(validator.isValid(json));
}
@Test
public void givenValidArrayJson_whenValidatingNonStrict_thenValid() {
String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]";
assertTrue(validator.isValid(json));
}
@Test
public void givenInvalidJson_whenValidatingNonStrict_thenValid() {
String json = "Invalid_Json";
assertTrue(validator.isValid(json));
}
@Test
public void givenInvalidJson_whenValidatingStrict_thenInvalid() {
String json = "Invalid_Json";
assertFalse(validator.isValidStrict(json));
}
}
@@ -0,0 +1,29 @@
package com.baeldung.jsonvalidation;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class JacksonValidatorUnitTest {
private final JacksonValidator validator = new JacksonValidator();
@Test
public void givenValidObjectJson_whenValidating_thenValid() {
String json = "{\"email\": \"example@com\", \"name\": \"John\"}";
assertTrue(validator.isValid(json));
}
@Test
public void givenValidArrayJson_whenValidating_thenValid() {
String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]";
assertTrue(validator.isValid(json));
}
@Test
public void givenInvalidJson_whenValidating_thenInvalid() {
String json = "Invalid_Json";
assertFalse(validator.isValid(json));
}
}
@@ -0,0 +1,35 @@
package com.baeldung.jsonvalidation;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class JsonValidatorUnitTest {
private final JsonValidator validator = new JsonValidator();
@Test
public void givenValidObjectJson_whenValidatingObject_thenValid() {
String json = "{\"email\": \"example@com\", \"name\": \"John\"}";
assertTrue(validator.isValidObject(json));
}
@Test
public void givenInvalidJson_whenValidating_thenInvalid() {
String json = "Invalid_Json";
assertFalse(validator.isValidObject(json));
}
@Test
public void givenValidArrayJson_whenValidatingObject_thenInvalid() {
String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]";
assertFalse(validator.isValidObject(json));
}
@Test
public void givenValidJson_whenValidatingJson_thenValid() {
String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]";
assertTrue(validator.isValidJson(json));
}
}
@@ -0,0 +1,105 @@
package com.baeldung.moshi;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.time.Instant;
import com.squareup.moshi.FromJson;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.JsonQualifier;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.ToJson;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.junit.Test;
public class AlternativeAdapterUnitTest {
@Test
public void whenSerializing_thenAlternativeAdapterUsed() {
Moshi moshi = new Moshi.Builder()
.add(new EpochMillisAdapter())
.build();
JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);
String json = jsonAdapter.toJson(new Post("Introduction to Moshi Json", "Baeldung", Instant.now()));
System.out.println(json);
}
@Test
public void whenDeserializing_thenAlternativeAdapterUsed() throws IOException {
Moshi moshi = new Moshi.Builder()
.add(new EpochMillisAdapter())
.build();
JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);
String json = "{\"author\":\"Baeldung\",\"posted\":1582095269204,\"title\":\"Introduction to Moshi Json\"}";
Post post = jsonAdapter.fromJson(json);
System.out.println(post);
}
public static class Post {
String title;
String author;
@EpochMillis Instant posted;
public Post() {
}
public Post(String title, String author, Instant posted) {
this.title = title;
this.author = author;
this.posted = posted;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Instant getPosted() {
return posted;
}
public void setPosted(Instant posted) {
this.posted = posted;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("title", title).append("author", author).append("posted", posted)
.toString();
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@JsonQualifier
public @interface EpochMillis {
}
public static class EpochMillisAdapter {
@ToJson
public Long toJson(@EpochMillis Instant input) {
return input.toEpochMilli();
}
@FromJson
@EpochMillis
public Instant fromJson(Long input) {
return Instant.ofEpochMilli(input);
}
}
}
@@ -0,0 +1,36 @@
package com.baeldung.moshi;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;
import org.junit.Test;
public class ArrayUnitTest {
@Test
public void whenSerializingList_thenJsonArrayProduced() {
Moshi moshi = new Moshi.Builder()
.build();
Type type = Types.newParameterizedType(List.class, String.class);
JsonAdapter<List<String>> jsonAdapter = moshi.adapter(type);
String json = jsonAdapter.toJson(Arrays.asList("One", "Two", "Three"));
System.out.println(json);
}
@Test
public void whenDeserializingJsonArray_thenListProduced() throws IOException {
Moshi moshi = new Moshi.Builder()
.build();
Type type = Types.newParameterizedType(List.class, String.class);
JsonAdapter<List<String>> jsonAdapter = moshi.adapter(type);
String json = "[\"One\",\"Two\",\"Three\"]";
List<String> result = jsonAdapter.fromJson(json);
System.out.println(result);
}
}
@@ -0,0 +1,94 @@
package com.baeldung.moshi;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import com.squareup.moshi.FromJson;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.ToJson;
import org.junit.Test;
public class ComplexAdapterUnitTest {
@Test
public void whenSerializing_thenCorrectJsonProduced() {
Moshi moshi = new Moshi.Builder()
.add(new JsonDateTimeAdapter())
.build();
JsonAdapter<ZonedDateTime> jsonAdapter = moshi.adapter(ZonedDateTime.class);
String json = jsonAdapter.toJson(ZonedDateTime.now());
System.out.println(json);
}
@Test
public void whenDeserializing_thenCorrectJsonConsumed() throws IOException {
Moshi moshi = new Moshi.Builder()
.add(new JsonDateTimeAdapter())
.build();
JsonAdapter<ZonedDateTime> jsonAdapter = moshi.adapter(ZonedDateTime.class);
String json = "{\"date\":\"2020-02-17\",\"time\":\"07:53:27.064\",\"timezone\":\"Europe/London\"}";
ZonedDateTime now = jsonAdapter.fromJson(json);
System.out.println(now);
}
public static class JsonDateTimeAdapter {
@ToJson
public JsonDateTime toJson(ZonedDateTime input) {
String date = input.toLocalDate().toString();
String time = input.toLocalTime().toString();
String timezone = input.getZone().toString();
return new JsonDateTime(date, time, timezone);
}
@FromJson
public ZonedDateTime fromJson(JsonDateTime input) {
LocalDate date = LocalDate.parse(input.getDate());
LocalTime time = LocalTime.parse(input.getTime());
ZoneId timezone = ZoneId.of(input.getTimezone());
return ZonedDateTime.of(date, time, timezone);
}
}
public static class JsonDateTime {
private String date;
private String time;
private String timezone;
public JsonDateTime() {
}
public JsonDateTime(String date, String time, String timezone) {
this.date = date;
this.time = time;
this.timezone = timezone;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
}
}
@@ -0,0 +1,68 @@
package com.baeldung.moshi;
import java.io.IOException;
import java.time.Instant;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.junit.Test;
public class DefaultUnitTest {
@Test
public void whenDeserializing_thenFieldsGetDefaultValues() throws IOException {
Moshi moshi = new Moshi.Builder()
.build();
JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);
String json = "{\"title\":\"My Post\"}";
Post post = jsonAdapter.fromJson(json);
System.out.println(post);
}
public static class Post {
private String title;
private String author;
private String posted;
public Post() {
posted = Instant.now().toString();
}
public Post(String title, String author, String posted) {
this.title = title;
this.author = author;
this.posted = posted;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPosted() {
return posted;
}
public void setPosted(String posted) {
this.posted = posted;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("title", title).append("author", author).append("posted", posted)
.toString();
}
}
}
@@ -0,0 +1,77 @@
package com.baeldung.moshi;
import java.io.IOException;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.junit.Test;
public class PrimitiveUnitTest {
@Test
public void whenSerializing_thenCorrectJsonProduced() {
Moshi moshi = new Moshi.Builder()
.build();
JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);
Post post = new Post("My Post", "Baeldung", "This is my post");
String json = jsonAdapter.toJson(post);
System.out.println(json);
}
@Test
public void whenDeserializing_thenCorrectJsonConsumed() throws IOException {
Moshi moshi = new Moshi.Builder()
.build();
JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);
String json = "{\"author\":\"Baeldung\",\"text\":\"This is my post\",\"title\":\"My Post\"}";
Post post = jsonAdapter.fromJson(json);
System.out.println(post);
}
public static class Post {
private String title;
private String author;
private String text;
public Post() {
}
public Post(String title, String author, String text) {
this.title = title;
this.author = author;
this.text = text;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("title", title).append("author", author).append("text", text)
.toString();
}
}
}
@@ -0,0 +1,68 @@
package com.baeldung.moshi;
import java.io.IOException;
import com.squareup.moshi.Json;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.junit.jupiter.api.Test;
public class RenameUnitTest {
@Test
public void whenSerializing_thenFieldsGetRenamed() {
Moshi moshi = new Moshi.Builder()
.build();
JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);
Post post = new Post("My Post", "Baeldung");
String json = jsonAdapter.toJson(post);
System.out.println(json);
}
@Test
public void whenSerializing_thenRenamedFieldsGetConsumed() throws IOException {
Moshi moshi = new Moshi.Builder()
.build();
JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);
String json = "{\"authored_by\":\"Baeldung\",\"title\":\"My Post\"}";
Post post = jsonAdapter.fromJson(json);
System.out.println(post);
}
public static class Post {
private String title;
@Json(name = "authored_by")
private String author;
public Post() {
}
public Post(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("title", title).append("author", author).toString();
}
}
}
@@ -0,0 +1,129 @@
package com.baeldung.moshi;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.squareup.moshi.FromJson;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.ToJson;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.junit.Test;
public class SimpleAdapterUnitTest {
@Test
public void whenSerializing_thenAdapterUsed() {
Moshi moshi = new Moshi.Builder()
.add(new AuthorAdapter())
.build();
JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);
Post post = new Post("My Post", new Author("Baeldung", "baeldung@example.com"), "This is my post");
String json = jsonAdapter.toJson(post);
System.out.println(json);
}
@Test
public void whenDeserializing_thenAdapterUsed() throws IOException {
Moshi moshi = new Moshi.Builder()
.add(new AuthorAdapter())
.build();
JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);
String json = "{\"author\":\"Baeldung <baeldung@example.com>\",\"text\":\"This is my post\",\"title\":\"My Post\"}";
Post post = jsonAdapter.fromJson(json);
System.out.println(post);
}
public static class AuthorAdapter {
private Pattern pattern = Pattern.compile("^(.*) <(.*)>$");
@ToJson
public String toJson(Author author) {
return author.name + " <" + author.email + ">";
}
@FromJson
public Author fromJson(String author) {
Matcher matcher = pattern.matcher(author);
return matcher.find() ? new Author(matcher.group(1), matcher.group(2)) : null;
}
}
public static class Author {
private String name;
private String email;
public Author() {
}
public Author(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("name", name).append("email", email).toString();
}
}
public static class Post {
private String title;
private Author author;
private String text;
public Post() {
}
public Post(String title, Author author, String text) {
this.title = title;
this.author = author;
this.text = text;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("title", title).append("author", author).append("text", text)
.toString();
}
}
}
@@ -0,0 +1,66 @@
package com.baeldung.moshi;
import java.io.IOException;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.junit.jupiter.api.Test;
public class TransientUnitTest {
@Test
public void whenSerializing_thenTransientFieldIgnored() {
Moshi moshi = new Moshi.Builder()
.build();
JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);
Post post = new Post("My Post", "Baeldung");
String json = jsonAdapter.toJson(post);
System.out.println(json);
}
@Test
public void whenDeserializing_thenTransientFieldIgnored() throws IOException {
Moshi moshi = new Moshi.Builder()
.build();
JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);
String json = "{\"authored_by\":\"Baeldung\",\"title\":\"My Post\"}";
Post post = jsonAdapter.fromJson(json);
System.out.println(post);
}
public static class Post {
private String title;
private transient String author;
public Post() {
}
public Post(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("title", title).append("author", author).toString();
}
}
}
@@ -0,0 +1 @@
{"id":1,"name":{"firstName": "Joe", "surname":"Blogg"}}
@@ -0,0 +1,213 @@
package com.baeldung.jsontojavaclass.pojo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"name",
"area",
"author",
"id",
"salary",
"topics"
})
@Generated("jsonschema2pojo")
public class SamplePojo {
@JsonProperty("name")
private String name;
@JsonProperty("area")
private String area;
@JsonProperty("author")
private String author;
@JsonProperty("id")
private Integer id;
@JsonProperty("salary")
private Integer salary;
@JsonProperty("topics")
private List<String> topics = new ArrayList<String>();
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
public SamplePojo withName(String name) {
this.name = name;
return this;
}
@JsonProperty("area")
public String getArea() {
return area;
}
@JsonProperty("area")
public void setArea(String area) {
this.area = area;
}
public SamplePojo withArea(String area) {
this.area = area;
return this;
}
@JsonProperty("author")
public String getAuthor() {
return author;
}
@JsonProperty("author")
public void setAuthor(String author) {
this.author = author;
}
public SamplePojo withAuthor(String author) {
this.author = author;
return this;
}
@JsonProperty("id")
public Integer getId() {
return id;
}
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
public SamplePojo withId(Integer id) {
this.id = id;
return this;
}
@JsonProperty("salary")
public Integer getSalary() {
return salary;
}
@JsonProperty("salary")
public void setSalary(Integer salary) {
this.salary = salary;
}
public SamplePojo withSalary(Integer salary) {
this.salary = salary;
return this;
}
@JsonProperty("topics")
public List<String> getTopics() {
return topics;
}
@JsonProperty("topics")
public void setTopics(List<String> topics) {
this.topics = topics;
}
public SamplePojo withTopics(List<String> topics) {
this.topics = topics;
return this;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public SamplePojo withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(SamplePojo.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');
sb.append("name");
sb.append('=');
sb.append(((this.name == null)?"<null>":this.name));
sb.append(',');
sb.append("area");
sb.append('=');
sb.append(((this.area == null)?"<null>":this.area));
sb.append(',');
sb.append("author");
sb.append('=');
sb.append(((this.author == null)?"<null>":this.author));
sb.append(',');
sb.append("id");
sb.append('=');
sb.append(((this.id == null)?"<null>":this.id));
sb.append(',');
sb.append("salary");
sb.append('=');
sb.append(((this.salary == null)?"<null>":this.salary));
sb.append(',');
sb.append("topics");
sb.append('=');
sb.append(((this.topics == null)?"<null>":this.topics));
sb.append(',');
sb.append("additionalProperties");
sb.append('=');
sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));
sb.append(',');
if (sb.charAt((sb.length()- 1)) == ',') {
sb.setCharAt((sb.length()- 1), ']');
} else {
sb.append(']');
}
return sb.toString();
}
@Override
public int hashCode() {
int result = 1;
result = ((result* 31)+((this.area == null)? 0 :this.area.hashCode()));
result = ((result* 31)+((this.author == null)? 0 :this.author.hashCode()));
result = ((result* 31)+((this.topics == null)? 0 :this.topics.hashCode()));
result = ((result* 31)+((this.name == null)? 0 :this.name.hashCode()));
result = ((result* 31)+((this.id == null)? 0 :this.id.hashCode()));
result = ((result* 31)+((this.additionalProperties == null)? 0 :this.additionalProperties.hashCode()));
result = ((result* 31)+((this.salary == null)? 0 :this.salary.hashCode()));
return result;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof SamplePojo) == false) {
return false;
}
SamplePojo rhs = ((SamplePojo) other);
return ((((((((this.area == rhs.area)||((this.area!= null)&&this.area.equals(rhs.area)))&&((this.author == rhs.author)||((this.author!= null)&&this.author.equals(rhs.author))))&&((this.topics == rhs.topics)||((this.topics!= null)&&this.topics.equals(rhs.topics))))&&((this.name == rhs.name)||((this.name!= null)&&this.name.equals(rhs.name))))&&((this.id == rhs.id)||((this.id!= null)&&this.id.equals(rhs.id))))&&((this.additionalProperties == rhs.additionalProperties)||((this.additionalProperties!= null)&&this.additionalProperties.equals(rhs.additionalProperties))))&&((this.salary == rhs.salary)||((this.salary!= null)&&this.salary.equals(rhs.salary))));
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,13 @@
{
"name": "Baeldung",
"area": "tech blogs",
"author": "Eugen",
"id": 32134,
"salary": 70000,
"topics": [
"java",
"kotlin",
"cs",
"linux"
]
}