YuCheng Hu 2024-05-03 11:59:06 -04:00
parent 1bad34f3db
commit 145d313fb7
Signed by: honeymoose
GPG Key ID: D74AE0B33A8002EC
68 changed files with 211 additions and 1643 deletions

View File

@ -7,12 +7,14 @@
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="jackson-annotations" />
<module name="assertion-libraries" />
<module name="core-java-serialization" />
<module name="core-java-annotations" />
<module name="core-java-uuid" />
<module name="core-java-numbers" />
<module name="core-java-strings" />
<module name="jackson" />
<module name="core-java-11" />
<module name="core-java-collections-conversions" />
<module name="core-java-collections" />
@ -22,6 +24,7 @@
<module name="activejdbc" />
<module name="spring-data-jpa-repo" />
<module name="apache-velocity" />
<module name="jackson-conversions-2" />
<module name="codebank" />
<module name="core-java-collections-list" />
<module name="image-compressing" />
@ -33,12 +36,15 @@
<module name="image-processing" />
<module name="spring-data-redis" />
<module name="core-java" />
<module name="jackson-custom-conversions" />
<module name="core-java-collections-list-2" />
<module name="core-java-collections-conversions-2" />
<module name="jackson-exceptions" />
<module name="core-java-8" />
<module name="apache-httpclient" />
<module name="core-java-collections-3" />
<module name="core-java-9" />
<module name="jackson-conversions" />
<module name="core-java-collections-2" />
</profile>
</annotationProcessing>

View File

@ -63,6 +63,22 @@
<file url="file://$PROJECT_DIR$/image-compressing/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/image-processing/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/image-processing/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-annotations/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-annotations/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-conversions-2/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-conversions-2/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-conversions/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-conversions/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-custom-conversions/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-custom-conversions/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-exceptions/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-exceptions/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-jr/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-jr/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/parent-boot-2/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/parent-boot-2/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/parent-boot-3/src/main/java" charset="UTF-8" />

View File

@ -1,29 +0,0 @@
package com.baeldung.jackson.bidirection;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public class CustomListDeserializer extends StdDeserializer<List<ItemWithSerializer>> {
private static final long serialVersionUID = 1095767961632979804L;
public CustomListDeserializer() {
this(null);
}
public CustomListDeserializer(final Class<?> vc) {
super(vc);
}
@Override
public List<ItemWithSerializer> deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException {
return new ArrayList<ItemWithSerializer>();
}
}

View File

@ -1,32 +0,0 @@
package com.baeldung.jackson.bidirection;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class CustomListSerializer extends StdSerializer<List<ItemWithSerializer>> {
private static final long serialVersionUID = 3698763098000900856L;
public CustomListSerializer() {
this(null);
}
public CustomListSerializer(final Class<List<ItemWithSerializer>> t) {
super(t);
}
@Override
public void serialize(final List<ItemWithSerializer> items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {
final List<Integer> ids = new ArrayList<Integer>();
for (final ItemWithSerializer item : items) {
ids.add(item.id);
}
generator.writeObject(ids);
}
}

View File

@ -1,17 +0,0 @@
package com.baeldung.jackson.bidirection;
public class Item {
public int id;
public String itemName;
public User owner;
public Item() {
super();
}
public Item(final int id, final String itemName, final User owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}

View File

@ -1,21 +0,0 @@
package com.baeldung.jackson.bidirection;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class ItemWithIdentity {
public int id;
public String itemName;
public UserWithIdentity owner;
public ItemWithIdentity() {
super();
}
public ItemWithIdentity(final int id, final String itemName, final UserWithIdentity owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}

View File

@ -1,17 +0,0 @@
package com.baeldung.jackson.bidirection;
public class ItemWithIgnore {
public int id;
public String itemName;
public UserWithIgnore owner;
public ItemWithIgnore() {
super();
}
public ItemWithIgnore(final int id, final String itemName, final UserWithIgnore owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}

View File

@ -1,21 +0,0 @@
package com.baeldung.jackson.bidirection;
import com.fasterxml.jackson.annotation.JsonBackReference;
public class ItemWithRef {
public int id;
public String itemName;
@JsonBackReference
public UserWithRef owner;
public ItemWithRef() {
super();
}
public ItemWithRef(final int id, final String itemName, final UserWithRef owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}

View File

@ -1,17 +0,0 @@
package com.baeldung.jackson.bidirection;
public class ItemWithSerializer {
public int id;
public String itemName;
public UserWithSerializer owner;
public ItemWithSerializer() {
super();
}
public ItemWithSerializer(final int id, final String itemName, final UserWithSerializer owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}

View File

@ -1,26 +0,0 @@
package com.baeldung.jackson.bidirection;
import com.baeldung.jackson.bidirection.jsonview.Views;
import com.fasterxml.jackson.annotation.JsonView;
public class ItemWithView {
@JsonView(Views.Public.class)
public int id;
@JsonView(Views.Public.class)
public String itemName;
@JsonView(Views.Public.class)
public UserWithView owner;
public ItemWithView() {
super();
}
public ItemWithView(final int id, final String itemName, final UserWithView owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}

View File

@ -1,24 +0,0 @@
package com.baeldung.jackson.bidirection;
import java.util.ArrayList;
import java.util.List;
public class User {
public int id;
public String name;
public List<Item> userItems;
public User() {
super();
}
public User(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<Item>();
}
public void addItem(final Item item) {
userItems.add(item);
}
}

View File

@ -1,28 +0,0 @@
package com.baeldung.jackson.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class UserWithIdentity {
public int id;
public String name;
public List<ItemWithIdentity> userItems;
public UserWithIdentity() {
super();
}
public UserWithIdentity(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<ItemWithIdentity>();
}
public void addItem(final ItemWithIdentity item) {
userItems.add(item);
}
}

View File

@ -1,28 +0,0 @@
package com.baeldung.jackson.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class UserWithIgnore {
public int id;
public String name;
@JsonIgnore
public List<ItemWithIgnore> userItems;
public UserWithIgnore() {
super();
}
public UserWithIgnore(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<ItemWithIgnore>();
}
public void addItem(final ItemWithIgnore item) {
userItems.add(item);
}
}

View File

@ -1,28 +0,0 @@
package com.baeldung.jackson.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonManagedReference;
public class UserWithRef {
public int id;
public String name;
@JsonManagedReference
public List<ItemWithRef> userItems;
public UserWithRef() {
super();
}
public UserWithRef(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<>();
}
public void addItem(final ItemWithRef item) {
userItems.add(item);
}
}

View File

@ -1,30 +0,0 @@
package com.baeldung.jackson.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public class UserWithSerializer {
public int id;
public String name;
@JsonSerialize(using = CustomListSerializer.class)
@JsonDeserialize(using = CustomListDeserializer.class)
public List<ItemWithSerializer> userItems;
public UserWithSerializer() {
super();
}
public UserWithSerializer(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<ItemWithSerializer>();
}
public void addItem(final ItemWithSerializer item) {
userItems.add(item);
}
}

View File

@ -1,33 +0,0 @@
package com.baeldung.jackson.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.jackson.bidirection.jsonview.Views;
import com.fasterxml.jackson.annotation.JsonView;
public class UserWithView {
@JsonView(Views.Public.class)
public int id;
@JsonView(Views.Public.class)
public String name;
@JsonView(Views.Internal.class)
public List<ItemWithView> userItems;
public UserWithView() {
super();
}
public UserWithView(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<ItemWithView>();
}
public void addItem(final ItemWithView item) {
userItems.add(item);
}
}

View File

@ -1,9 +0,0 @@
package com.baeldung.jackson.bidirection.jsonview;
public class Views {
public static class Public {
}
public static class Internal extends Public {
}
}

View File

@ -1,5 +0,0 @@
package com.baeldung.jackson.deductionbasedpolymorphism;
public class ImperialSpy implements Character {
}

View File

@ -1,30 +0,0 @@
package com.baeldung.jackson.domain;
public class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

View File

@ -1,100 +0,0 @@
package com.baeldung.jackson.format;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class User {
private String firstName;
private String lastName;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
private Date createdDate;
public User() {
}
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.createdDate = new Date();
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getCreatedDate() {
return createdDate;
}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB")
public Date getCurrentDate() {
return new Date();
}
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
public Date getDateNum() {
return new Date();
}
}
@JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
class UserIgnoreCase {
private String firstName;
private String lastName;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
private Date createdDate;
public UserIgnoreCase() {
}
public UserIgnoreCase(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.createdDate = new Date();
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getCreatedDate() {
return createdDate;
}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB")
public Date getCurrentDate() {
return new Date();
}
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
public Date getDateNum() {
return new Date();
}
}

View File

@ -1,13 +0,0 @@
package com.baeldung.jackson.jsonignorevstransient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -1,8 +0,0 @@
package com.baeldung.jackson.jsonignorevstransient;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

View File

@ -1,36 +0,0 @@
package com.baeldung.jackson.jsonview;
import com.fasterxml.jackson.annotation.JsonView;
public class Item {
@JsonView(Views.Public.class)
public int id;
@JsonView(Views.Public.class)
public String itemName;
@JsonView(Views.Internal.class)
public String ownerName;
public Item() {
super();
}
public Item(final int id, final String itemName, final String ownerName) {
this.id = id;
this.itemName = itemName;
this.ownerName = ownerName;
}
public int getId() {
return id;
}
public String getItemName() {
return itemName;
}
public String getOwnerName() {
return ownerName;
}
}

View File

@ -1,22 +0,0 @@
package com.baeldung.jackson.jsonview;
import java.util.List;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
public class MyBeanSerializerModifier extends BeanSerializerModifier {
@Override
public List<BeanPropertyWriter> changeProperties(final SerializationConfig config, final BeanDescription beanDesc, final List<BeanPropertyWriter> beanProperties) {
for (int i = 0; i < beanProperties.size(); i++) {
final BeanPropertyWriter beanPropertyWriter = beanProperties.get(i);
if (beanPropertyWriter.getName() == "name") {
beanProperties.set(i, new UpperCasingWriter(beanPropertyWriter));
}
}
return beanProperties;
}
}

View File

@ -1,21 +0,0 @@
package com.baeldung.jackson.jsonview;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
public class UpperCasingWriter extends BeanPropertyWriter {
final BeanPropertyWriter _writer;
public UpperCasingWriter(final BeanPropertyWriter w) {
super(w);
_writer = w;
}
@Override
public void serializeAsField(final Object bean, final JsonGenerator gen, final SerializerProvider prov) throws Exception {
String value = ((User) bean).name;
value = (value == null) ? "" : value.toUpperCase();
gen.writeStringField("name", value);
}
}

View File

@ -1,27 +0,0 @@
package com.baeldung.jackson.jsonview;
import com.fasterxml.jackson.annotation.JsonView;
public class User {
public int id;
@JsonView(Views.Public.class)
public String name;
public User() {
super();
}
public User(final int id, final String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}

View File

@ -1,9 +0,0 @@
package com.baeldung.jackson.jsonview;
public class Views {
public static class Public {
}
public static class Internal extends Public {
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deductionbasedpolymorphism;
package com.ossez.jackson.deductionbasedpolymorphism;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deductionbasedpolymorphism;
package com.ossez.jackson.deductionbasedpolymorphism;
public class ControlledCharacter {

View File

@ -0,0 +1,5 @@
package com.ossez.jackson.deductionbasedpolymorphism;
public class ImperialSpy implements Character {
}

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deductionbasedpolymorphism;
package com.ossez.jackson.deductionbasedpolymorphism;
public class King extends NamedCharacter {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deductionbasedpolymorphism;
package com.ossez.jackson.deductionbasedpolymorphism;
public class Knight extends NamedCharacter {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deductionbasedpolymorphism;
package com.ossez.jackson.deductionbasedpolymorphism;
public class NamedCharacter implements Character {

View File

@ -0,0 +1,13 @@
package com.ossez.jackson.jsonignorevstransient;
//import org.springframework.boot.SpringApplication;
//import org.springframework.boot.autoconfigure.SpringBootApplication;
//@SpringBootApplication
public class Application {
// public static void main(String[] args) {
// SpringApplication.run(Application.class, args);
// }
}

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.jsonignorevstransient;
package com.ossez.jackson.jsonignorevstransient;
import com.fasterxml.jackson.annotation.JsonIgnore;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.jsonignorevstransient;
package com.ossez.jackson.jsonignorevstransient;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;

View File

@ -0,0 +1,8 @@
package com.ossez.jackson.jsonignorevstransient;
//import org.springframework.data.jpa.repository.JpaRepository;
//import org.springframework.stereotype.Repository;
//@Repository
//public interface UserRepository extends JpaRepository<User, Long> {
//}

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.jsonmerge;
package com.ossez.jackson.jsonmerge;
public class Keyboard {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.jsonmerge;
package com.ossez.jackson.jsonmerge;
import com.fasterxml.jackson.annotation.JsonMerge;

View File

@ -1,133 +0,0 @@
package com.baeldung.jackson.advancedannotations;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.jackson.advancedannotations.AppendBeans.BeanWithAppend;
import com.baeldung.jackson.advancedannotations.AppendBeans.BeanWithoutAppend;
import com.baeldung.jackson.advancedannotations.IdentityReferenceBeans.BeanWithIdentityReference;
import com.baeldung.jackson.advancedannotations.IdentityReferenceBeans.BeanWithoutIdentityReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper;
public class AdvancedAnnotationsUnitTest {
@Test
public void whenNotUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithoutIdentityReference bean = new BeanWithoutIdentityReference(1, "Bean Without Identity Reference Annotation");
String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("Bean Without Identity Reference Annotation"));
}
@Test
public void whenUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithIdentityReference bean = new BeanWithIdentityReference(1, "Bean With Identity Reference Annotation");
String jsonString = mapper.writeValueAsString(bean);
assertEquals("1", jsonString);
}
@Test
public void whenNotUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation");
ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class)
.withAttribute("version", "1.0");
String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, not(containsString("version")));
assertThat(jsonString, not(containsString("1.0")));
}
@Test
public void whenUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation");
ObjectWriter writer = mapper.writerFor(BeanWithAppend.class)
.withAttribute("version", "1.0");
String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, containsString("version"));
assertThat(jsonString, containsString("1.0"));
}
@Test
public void whenUsingJsonNamingAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
NamingBean bean = new NamingBean(3, "Naming Bean");
String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("bean_name"));
}
@Test
public void whenUsingJsonPropertyDescriptionAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
SchemaFactoryWrapper wrapper = new SchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(PropertyDescriptionBean.class, wrapper);
JsonSchema jsonSchema = wrapper.finalSchema();
String jsonString = mapper.writeValueAsString(jsonSchema);
System.out.println(jsonString);
assertThat(jsonString, containsString("This is a description of the name property"));
}
@Test
public void whenUsingJsonPOJOBuilderAnnotation_thenCorrect() throws IOException {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"id\":5,\"name\":\"POJO Builder Bean\"}";
POJOBuilderBean bean = mapper.readValue(jsonString, POJOBuilderBean.class);
assertEquals(5, bean.getIdentity());
assertEquals("POJO Builder Bean", bean.getBeanName());
}
@Test
public void whenUsingJsonTypeIdAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(DefaultTyping.NON_FINAL);
TypeIdBean bean = new TypeIdBean(6, "Type Id Bean");
String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("Type Id Bean"));
}
@Test
public void whenUsingJsonTypeIdResolverAnnotation_thenCorrect() throws IOException {
TypeIdResolverStructure.FirstBean bean1 = new TypeIdResolverStructure.FirstBean(1, "Bean 1");
TypeIdResolverStructure.LastBean bean2 = new TypeIdResolverStructure.LastBean(2, "Bean 2");
List<TypeIdResolverStructure.AbstractBean> beans = new ArrayList<>();
beans.add(bean1);
beans.add(bean2);
TypeIdResolverStructure.BeanContainer serializedContainer = new TypeIdResolverStructure.BeanContainer();
serializedContainer.setBeans(beans);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(serializedContainer);
assertThat(jsonString, containsString("bean1"));
assertThat(jsonString, containsString("bean2"));
TypeIdResolverStructure.BeanContainer deserializedContainer = mapper.readValue(jsonString, TypeIdResolverStructure.BeanContainer.class);
List<TypeIdResolverStructure.AbstractBean> beanList = deserializedContainer.getBeans();
assertThat(beanList.get(0), instanceOf(TypeIdResolverStructure.FirstBean.class));
assertThat(beanList.get(1), instanceOf(TypeIdResolverStructure.LastBean.class));
}
}

View File

@ -1,58 +0,0 @@
package com.baeldung.jackson.advancedannotations;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
public class AppendBeans {
public static class BeanWithoutAppend {
private int id;
private String name;
public BeanWithoutAppend(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@JsonAppend(attrs = { @JsonAppend.Attr(value = "version") })
public static class BeanWithAppend {
private int id;
private String name;
public BeanWithAppend(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}

View File

@ -1,62 +0,0 @@
package com.baeldung.jackson.advancedannotations;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
public class IdentityReferenceBeans {
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public static class BeanWithoutIdentityReference {
private int id;
private String name;
public BeanWithoutIdentityReference(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
public static class BeanWithIdentityReference {
private int id;
private String name;
public BeanWithIdentityReference(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}

View File

@ -1,31 +0,0 @@
package com.baeldung.jackson.advancedannotations;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class NamingBean {
private int id;
private String beanName;
public NamingBean(int id, String beanName) {
this.id = id;
this.beanName = beanName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
}

View File

@ -1,51 +0,0 @@
package com.baeldung.jackson.advancedannotations;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
@JsonDeserialize(builder = POJOBuilderBean.BeanBuilder.class)
public class POJOBuilderBean {
private int identity;
private String beanName;
@JsonPOJOBuilder(buildMethodName = "createBean", withPrefix = "construct")
public static class BeanBuilder {
private int idValue;
private String nameValue;
public BeanBuilder constructId(int id) {
idValue = id;
return this;
}
public BeanBuilder constructName(String name) {
nameValue = name;
return this;
}
public POJOBuilderBean createBean() {
return new POJOBuilderBean(idValue, nameValue);
}
}
public POJOBuilderBean(int identity, String beanName) {
this.identity = identity;
this.beanName = beanName;
}
public int getIdentity() {
return identity;
}
public void setIdentity(int identity) {
this.identity = identity;
}
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
}

View File

@ -1,25 +0,0 @@
package com.baeldung.jackson.advancedannotations;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
public class PropertyDescriptionBean {
private int id;
@JsonPropertyDescription("This is a description of the name property")
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,30 +0,0 @@
package com.baeldung.jackson.advancedannotations;
import com.fasterxml.jackson.annotation.JsonTypeId;
public class TypeIdBean {
private int id;
@JsonTypeId
private String name;
public TypeIdBean(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,130 +0,0 @@
package com.baeldung.jackson.advancedannotations;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver;
import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase;
public class TypeIdResolverStructure {
public static class BeanContainer {
private List<AbstractBean> beans;
public List<AbstractBean> getBeans() {
return beans;
}
public void setBeans(List<AbstractBean> beans) {
this.beans = beans;
}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@type")
@JsonTypeIdResolver(BeanIdResolver.class)
public static class AbstractBean {
private int id;
protected AbstractBean() {
}
protected AbstractBean(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public static class FirstBean extends AbstractBean {
String firstName;
public FirstBean() {
}
public FirstBean(int id, String name) {
super(id);
setFirstName(name);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String name) {
firstName = name;
}
}
public static class LastBean extends AbstractBean {
String lastName;
public LastBean() {
}
public LastBean(int id, String name) {
super(id);
setLastName(name);
}
public String getLastName() {
return lastName;
}
public void setLastName(String name) {
lastName = name;
}
}
public static class BeanIdResolver extends TypeIdResolverBase {
private JavaType superType;
@Override
public void init(JavaType baseType) {
superType = baseType;
}
@Override
public Id getMechanism() {
return Id.NAME;
}
@Override
public String idFromValue(Object obj) {
return idFromValueAndType(obj, obj.getClass());
}
@Override
public String idFromValueAndType(Object obj, Class<?> subType) {
String typeId = null;
switch (subType.getSimpleName()) {
case "FirstBean":
typeId = "bean1";
break;
case "LastBean":
typeId = "bean2";
}
return typeId;
}
@Override
public JavaType typeFromId(DatabindContext context, String id) {
Class<?> subType = null;
switch (id) {
case "bean1":
subType = FirstBean.class;
break;
case "bean2":
subType = LastBean.class;
}
return context.constructSpecializedType(superType, subType);
}
}
}

View File

@ -1,152 +0,0 @@
package com.baeldung.jackson.bidirection;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.baeldung.jackson.bidirection.jsonview.Views;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonBidirectionRelationUnitTest {
@Test (expected = JsonMappingException.class)
public void givenBidirectionRelation_whenSerializing_thenException() throws JsonProcessingException {
final User user = new User(1, "John");
final Item item = new Item(2, "book", user);
user.addItem(item);
new ObjectMapper().writeValueAsString(item);
}
@Test
public void givenBidirectionRelation_whenUsingJacksonReferenceAnnotationWithSerialization_thenCorrect() throws JsonProcessingException {
final UserWithRef user = new UserWithRef(1, "John");
final ItemWithRef item = new ItemWithRef(2, "book", user);
user.addItem(item);
final String itemJson = new ObjectMapper().writeValueAsString(item);
final String userJson = new ObjectMapper().writeValueAsString(user);
assertThat(itemJson, containsString("book"));
assertThat(itemJson, not(containsString("John")));
assertThat(userJson, containsString("John"));
assertThat(userJson, containsString("userItems"));
assertThat(userJson, containsString("book"));
}
@Test
public void givenBidirectionRelation_whenUsingJacksonReferenceAnnotationWithDeserialization_thenCorrect() throws JsonProcessingException {
final UserWithRef user = new UserWithRef(1, "John");
final ItemWithRef item = new ItemWithRef(2, "book", user);
user.addItem(item);
final String itemJson = new ObjectMapper().writeValueAsString(item);
final String userJson = new ObjectMapper().writeValueAsString(user);
final ItemWithRef itemRead = new ObjectMapper().readValue(itemJson, ItemWithRef.class);
final UserWithRef userRead = new ObjectMapper().readValue(userJson, UserWithRef.class);
assertThat(itemRead.itemName, is("book"));
assertThat(itemRead.owner, nullValue());
assertThat(userRead.name, is("John"));
assertThat(userRead.userItems.get(0).itemName, is("book"));
}
@Test
public void givenBidirectionRelation_whenUsingJsonIdentityInfo_thenCorrect() throws JsonProcessingException {
final UserWithIdentity user = new UserWithIdentity(1, "John");
final ItemWithIdentity item = new ItemWithIdentity(2, "book", user);
user.addItem(item);
final String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, containsString("userItems"));
}
@Test
public void givenBidirectionRelation_whenUsingJsonIgnore_thenCorrect() throws JsonProcessingException {
final UserWithIgnore user = new UserWithIgnore(1, "John");
final ItemWithIgnore item = new ItemWithIgnore(2, "book", user);
user.addItem(item);
final String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, not(containsString("userItems")));
}
@Test
public void givenBidirectionRelation_whenUsingCustomSerializer_thenCorrect() throws JsonProcessingException {
final UserWithSerializer user = new UserWithSerializer(1, "John");
final ItemWithSerializer item = new ItemWithSerializer(2, "book", user);
user.addItem(item);
final String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, containsString("userItems"));
}
@Test
public void givenBidirectionRelation_whenDeserializingUsingIdentity_thenCorrect() throws JsonProcessingException, IOException {
final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}";
final ItemWithIdentity item = new ObjectMapper().readerFor(ItemWithIdentity.class)
.readValue(json);
assertEquals(2, item.id);
assertEquals("book", item.itemName);
assertEquals("John", item.owner.name);
}
@Test
public void givenBidirectionRelation_whenUsingCustomDeserializer_thenCorrect() throws JsonProcessingException, IOException {
final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}";
final ItemWithSerializer item = new ObjectMapper().readerFor(ItemWithSerializer.class)
.readValue(json);
assertEquals(2, item.id);
assertEquals("book", item.itemName);
assertEquals("John", item.owner.name);
}
@Test
public void givenBidirectionRelation_whenUsingPublicJsonView_thenCorrect() throws JsonProcessingException {
final UserWithView user = new UserWithView(1, "John");
final ItemWithView item = new ItemWithView(2, "book", user);
user.addItem(item);
final String result = new ObjectMapper().writerWithView(Views.Public.class)
.writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, not(containsString("userItems")));
}
@Test(expected = JsonMappingException.class)
public void givenBidirectionRelation_whenUsingInternalJsonView_thenException() throws JsonProcessingException {
final UserWithView user = new UserWithView(1, "John");
final ItemWithView item = new ItemWithView(2, "book", user);
user.addItem(item);
new ObjectMapper().writerWithView(Views.Internal.class)
.writeValueAsString(item);
}
}

View File

@ -1,56 +0,0 @@
package com.baeldung.jackson.format;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.from;
import static org.assertj.core.data.Percentage.withPercentage;
public class JsonFormatUnitTest {
private static final String JSON_STRING = "{\"FIRSTNAME\":\"John\",\"lastname\":\"Smith\",\"cReAtEdDaTe\":\"2016-12-18@07:53:34.740+0000\"}";
@Test
public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingException {
User user = new User("Jay", "Sridhar");
String result = new ObjectMapper().writeValueAsString(user);
// Expected to match: "2016-12-19@09:34:42.628+0000"
assertThat(from(result).getString("createdDate")).matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}");
// Expected to be close to current time
long now = new Date().getTime();
assertThat(from(result).getLong("dateNum")).isCloseTo(now, withPercentage(10.0));
}
@Test
public void whenDeserializeJsonStrToUserObject_thenFail() {
assertThatThrownBy(() -> new ObjectMapper().readValue(JSON_STRING, User.class)).isInstanceOf(UnrecognizedPropertyException.class);
}
@Test
public void whenDeserializeJsonStrToUserIgnoreCaseObject_thenSuccess() throws JsonProcessingException, ParseException {
UserIgnoreCase result = new ObjectMapper().readValue(JSON_STRING, UserIgnoreCase.class);
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSzz");
Date expectedDate = fmt.parse("2016-12-18T07:53:34.740+0000");
assertThat(result)
.isNotNull()
.returns("John", from(UserIgnoreCase::getFirstName))
.returns("Smith", from(UserIgnoreCase::getLastName))
.returns(expectedDate, from(UserIgnoreCase::getCreatedDate));
}
}

View File

@ -1,39 +0,0 @@
package com.baeldung.jackson.jsonignorevstransient;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
@SpringBootTest
class UserUnitTest {
@Autowired
UserRepository userRepository;
@Test
void givenUser_whenSave_thenSkipTransientFields() {
User user = new User(1L, "user", "newPassword123", "newPassword123");
User savedUser = userRepository.save(user);
assertNotNull(savedUser);
assertNotNull(savedUser.getPassword());
assertNull(savedUser.getRepeatedPassword());
}
@Test
void givenUser_whenSerializing_thenTransientFieldNotIgnored() throws JsonProcessingException {
User user = new User(1L, "user", "newPassword123", "newPassword123");
String result = new ObjectMapper().writeValueAsString(user);
assertThat(result, containsString("user"));
assertThat(result, containsString("repeatedPassword"));
}
}

View File

@ -1,92 +0,0 @@
package com.baeldung.jackson.jsonview;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.baeldung.jackson.jsonview.Item;
import com.baeldung.jackson.jsonview.MyBeanSerializerModifier;
import com.baeldung.jackson.jsonview.User;
import com.baeldung.jackson.jsonview.Views;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.BeanSerializerFactory;
import com.fasterxml.jackson.databind.ser.SerializerFactory;
public class JacksonJsonViewUnitTest {
@Test
public void whenUseJsonViewToSerialize_thenCorrect() throws JsonProcessingException {
final User user = new User(1, "John");
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
final String result = mapper.writerWithView(Views.Public.class)
.writeValueAsString(user);
assertThat(result, containsString("John"));
assertThat(result, not(containsString("1")));
}
@Test
public void whenUsePublicView_thenOnlyPublicSerialized() throws JsonProcessingException {
final Item item = new Item(2, "book", "John");
final ObjectMapper mapper = new ObjectMapper();
final String result = mapper.writerWithView(Views.Public.class)
.writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("2"));
assertThat(result, not(containsString("John")));
}
@Test
public void whenUseInternalView_thenAllSerialized() throws JsonProcessingException {
final Item item = new Item(2, "book", "John");
final ObjectMapper mapper = new ObjectMapper();
final String result = mapper.writerWithView(Views.Internal.class)
.writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("2"));
assertThat(result, containsString("John"));
}
@Test
public void whenUseJsonViewToDeserialize_thenCorrect() throws IOException {
final String json = "{\"id\":1,\"name\":\"John\"}";
final ObjectMapper mapper = new ObjectMapper();
final User user = mapper.readerWithView(Views.Public.class)
.forType(User.class)
.readValue(json);
assertEquals(1, user.getId());
assertEquals("John", user.getName());
}
@Test
public void whenUseCustomJsonViewToSerialize_thenCorrect() throws JsonProcessingException {
final User user = new User(1, "John");
final SerializerFactory serializerFactory = BeanSerializerFactory.instance.withSerializerModifier(new MyBeanSerializerModifier());
final ObjectMapper mapper = new ObjectMapper();
mapper.setSerializerFactory(serializerFactory);
final String result = mapper.writerWithView(Views.Public.class)
.writeValueAsString(user);
assertThat(result, containsString("JOHN"));
assertThat(result, containsString("1"));
}
}

View File

@ -9,9 +9,9 @@ import static org.junit.Assert.assertThat;
import java.io.IOException;
import com.ossez.jackson.bidirection.jsonview.Views;
import org.junit.Test;
import com.ossez.jackson.bidirection.jsonview.Views;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

View File

@ -1,6 +1,6 @@
package com.baeldung.jackson.deductionbasedpolymorphism;
package com.ossez.jackson.deductionbasedpolymorphism;
import static com.baeldung.jackson.deductionbasedpolymorphism.JsonStringFormatterUtil.formatJson;
import static com.ossez.jackson.deductionbasedpolymorphism.JsonStringFormatterUtil.formatJson;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.deductionbasedpolymorphism;
package com.ossez.jackson.deductionbasedpolymorphism;
import static com.baeldung.jackson.deductionbasedpolymorphism.JsonStringFormatterUtil.formatJson;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
@ -18,10 +17,10 @@ class ContainedInferenceUnitTest {
@Test
void givenAKnightControlledCharacter_whenMapping_thenExpectAControlledCharacterWithKnight() throws Exception {
String controlledCharacterJson = formatJson("{'character': {'name': 'Ostrava, of Boletaria', 'weapon': 'Rune Sword'}}");
String controlledCharacterJson = JsonStringFormatterUtil.formatJson("{'character': {'name': 'Ostrava, of Boletaria', 'weapon': 'Rune Sword'}}");
ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class);
Character character = controlledCharacter.getCharacter();
com.ossez.jackson.deductionbasedpolymorphism.Character character = controlledCharacter.getCharacter();
assertTrue(character instanceof Knight);
assertSame(character.getClass(), Knight.class);
@ -32,7 +31,7 @@ class ContainedInferenceUnitTest {
@Test
void givenAKingControlledCharacter_whenMapping_thenExpectAControlledCharacterWithKing() throws Exception {
String controlledCharacterJson = formatJson("{'character': {'name': 'King Allant', 'land': 'Boletaria'}}");
String controlledCharacterJson = JsonStringFormatterUtil.formatJson("{'character': {'name': 'King Allant', 'land': 'Boletaria'}}");
ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class);
Character character = controlledCharacter.getCharacter();
@ -46,7 +45,7 @@ class ContainedInferenceUnitTest {
@Test
void givenAnEmptySubtype_whenMapping_thenExpectImperialSpy() throws Exception {
String controlledCharacterJson = formatJson("{'character': {}}");
String controlledCharacterJson = JsonStringFormatterUtil.formatJson("{'character': {}}");
ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class);
@ -55,7 +54,7 @@ class ContainedInferenceUnitTest {
@Test
void givenANullCharacter_whenMapping_thenExpectNullCharacter() throws Exception {
String controlledCharacterJson = formatJson("{'character': null}");
String controlledCharacterJson = JsonStringFormatterUtil.formatJson("{'character': null}");
ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class);
@ -64,7 +63,7 @@ class ContainedInferenceUnitTest {
@Test
void givenAAnAbsentCharacter_whenMapping_thenExpectNullCharacter() throws Exception {
String controlledCharacterJson = formatJson("{}");
String controlledCharacterJson = JsonStringFormatterUtil.formatJson("{}");
ControlledCharacter controlledCharacter = objectMapper.readValue(controlledCharacterJson, ControlledCharacter.class);

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deductionbasedpolymorphism;
package com.ossez.jackson.deductionbasedpolymorphism;
public class JsonStringFormatterUtil {

View File

@ -1,6 +1,5 @@
package com.baeldung.jackson.deductionbasedpolymorphism;
package com.ossez.jackson.deductionbasedpolymorphism;
import static com.baeldung.jackson.deductionbasedpolymorphism.JsonStringFormatterUtil.formatJson;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
@ -18,7 +17,7 @@ class SimpleInferenceUnitTest {
@Test
void givenAKnight_whenMapping_thenExpectAKnightType() throws Exception {
String knightJson = formatJson("{'name':'Ostrava, of Boletaria', 'weapon':'Rune Sword'}");
String knightJson = JsonStringFormatterUtil.formatJson("{'name':'Ostrava, of Boletaria', 'weapon':'Rune Sword'}");
Character character = objectMapper.readValue(knightJson, Character.class);
@ -31,7 +30,7 @@ class SimpleInferenceUnitTest {
@Test
void givenAKing_whenMapping_thenExpectAKingType() throws Exception {
String kingJson = formatJson("{'name':'Old King Allant', 'land':'Boletaria'}");
String kingJson = JsonStringFormatterUtil.formatJson("{'name':'Old King Allant', 'land':'Boletaria'}");
Character character = objectMapper.readValue(kingJson, Character.class);

View File

@ -1,7 +1,8 @@
package com.baeldung.jackson.jsonignorevstransient;
package com.ossez.jackson.jsonignorevstransient;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ossez.jackson.jsonignorevstransient.Person;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.jsonmerge;
package com.ossez.jackson.jsonmerge;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@ -6,6 +6,10 @@ import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import com.ossez.jackson.jsonmerge.Keyboard;
import com.ossez.jackson.jsonmerge.ObjectWithMap;
import com.ossez.jackson.jsonmerge.ProgrammerAnnotated;
import com.ossez.jackson.jsonmerge.ProgrammerNotAnnotated;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException;

View File

@ -9,7 +9,7 @@ import java.net.URL;
import java.nio.charset.Charset;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
//import org.json.JSONObject;
import com.fasterxml.jackson.core.exc.StreamReadException;
import com.fasterxml.jackson.databind.DatabindException;
@ -54,9 +54,9 @@ public class JsonUrlReader {
return get(url).toPrettyString();
}
public static JSONObject getJson(String url) throws MalformedURLException, IOException {
String json = IOUtils.toString(new URL(url), Charset.forName("UTF-8"));
JSONObject object = new JSONObject(json);
return object;
}
// public static JSONObject getJson(String url) throws MalformedURLException, IOException {
// String json = IOUtils.toString(new URL(url), Charset.forName("UTF-8"));
// JSONObject object = new JSONObject(json);
// return object;
// }
}

View File

@ -1,62 +1,62 @@
package com.baeldung.jackson.jsonurlreader;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import java.io.IOException;
import java.net.ServerSocket;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.mockserver.client.MockServerClient;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.HttpStatusCode;
import com.baeldung.jackson.jsonurlreader.data.Example;
public class JsonMockServer {
protected static final String JSON_RESPONSE = "{ \"name\": \"A\", \"n\": 1, \"real\": true }";
protected static final Example OBJECT_RESPONSE = new Example("A", 1, true);
protected static String serviceUrl;
private static final String SERVER_ADDRESS = "127.0.0.1";
private static final String PATH = "/sample-json";
private static ClientAndServer mockServer;
private static int serverPort;
@BeforeAll
static void startServer() throws IOException {
serverPort = getFreePort();
serviceUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH;
mockServer = startClientAndServer(serverPort);
mockJsonRequest();
}
@AfterAll
static void stopServer() {
mockServer.stop();
}
@SuppressWarnings("resource")
private static void mockJsonRequest() {
new MockServerClient(SERVER_ADDRESS, serverPort)
.when(request()
.withPath(PATH)
.withMethod("GET"))
.respond(response()
.withStatusCode(HttpStatusCode.OK_200.code())
.withBody(JSON_RESPONSE)
);
}
private static int getFreePort() throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
return serverSocket.getLocalPort();
}
}
}
//package com.baeldung.jackson.jsonurlreader;
//
//import static org.mockserver.integration.ClientAndServer.startClientAndServer;
//import static org.mockserver.model.HttpRequest.request;
//import static org.mockserver.model.HttpResponse.response;
//
//import java.io.IOException;
//import java.net.ServerSocket;
//
//import org.junit.jupiter.api.AfterAll;
//import org.junit.jupiter.api.BeforeAll;
//import org.mockserver.client.MockServerClient;
//import org.mockserver.integration.ClientAndServer;
//import org.mockserver.model.HttpStatusCode;
//
//import com.baeldung.jackson.jsonurlreader.data.Example;
//
//public class JsonMockServer {
// protected static final String JSON_RESPONSE = "{ \"name\": \"A\", \"n\": 1, \"real\": true }";
// protected static final Example OBJECT_RESPONSE = new Example("A", 1, true);
//
// protected static String serviceUrl;
//
// private static final String SERVER_ADDRESS = "127.0.0.1";
// private static final String PATH = "/sample-json";
//
// private static ClientAndServer mockServer;
// private static int serverPort;
//
// @BeforeAll
// static void startServer() throws IOException {
// serverPort = getFreePort();
// serviceUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH;
//
// mockServer = startClientAndServer(serverPort);
//
// mockJsonRequest();
// }
//
// @AfterAll
// static void stopServer() {
// mockServer.stop();
// }
//
// @SuppressWarnings("resource")
// private static void mockJsonRequest() {
// new MockServerClient(SERVER_ADDRESS, serverPort)
// .when(request()
// .withPath(PATH)
// .withMethod("GET"))
// .respond(response()
// .withStatusCode(HttpStatusCode.OK_200.code())
// .withBody(JSON_RESPONSE)
// );
// }
//
// private static int getFreePort() throws IOException {
// try (ServerSocket serverSocket = new ServerSocket(0)) {
// return serverSocket.getLocalPort();
// }
// }
//}

View File

@ -1,50 +1,50 @@
package com.baeldung.jackson.jsonurlreader;
import static org.junit.Assert.assertEquals;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import com.baeldung.jackson.jsonurlreader.data.Example;
import com.fasterxml.jackson.databind.JsonNode;
public class JsonUrlReaderIntegrationTest extends JsonMockServer {
@Test
public void whenStreamUrl_thenJsonStringReturned() throws Exception {
String jsonNode = JsonUrlReader.stream(serviceUrl);
assertEquals(jsonNode, JSON_RESPONSE);
}
@Test
public void whenGetUrl_thenJsonNodeReturned() throws Exception {
JsonNode jsonNode = JsonUrlReader.get(serviceUrl);
assertEquals(jsonNode.get("name")
.textValue(), "A");
assertEquals(jsonNode.get("n")
.intValue(), 1);
assertEquals(jsonNode.get("real")
.booleanValue(), true);
}
@Test
public void givenType_whenGetUrl_thenTypeReturned() throws Exception {
Example object = JsonUrlReader.get(serviceUrl, Example.class);
Integer n = 1;
assertEquals(object.getName(), "A");
assertEquals(object.getN(), n);
assertEquals(object.getReal(), true);
}
@Test
public void whenGetJsonUrl_thenJsonObjectReturned() throws Exception {
JSONObject jsonObject = JsonUrlReader.getJson(serviceUrl);
assertEquals(jsonObject.getString("name"), "A");
assertEquals(jsonObject.getInt("n"), 1);
assertEquals(jsonObject.getBoolean("real"), true);
}
}
//package com.baeldung.jackson.jsonurlreader;
//
//import static org.junit.Assert.assertEquals;
//
//import org.json.JSONObject;
//import org.junit.jupiter.api.Test;
//
//import com.baeldung.jackson.jsonurlreader.data.Example;
//import com.fasterxml.jackson.databind.JsonNode;
//
//public class JsonUrlReaderIntegrationTest extends JsonMockServer {
//
// @Test
// public void whenStreamUrl_thenJsonStringReturned() throws Exception {
// String jsonNode = JsonUrlReader.stream(serviceUrl);
//
// assertEquals(jsonNode, JSON_RESPONSE);
// }
//
// @Test
// public void whenGetUrl_thenJsonNodeReturned() throws Exception {
// JsonNode jsonNode = JsonUrlReader.get(serviceUrl);
//
// assertEquals(jsonNode.get("name")
// .textValue(), "A");
// assertEquals(jsonNode.get("n")
// .intValue(), 1);
// assertEquals(jsonNode.get("real")
// .booleanValue(), true);
// }
//
// @Test
// public void givenType_whenGetUrl_thenTypeReturned() throws Exception {
// Example object = JsonUrlReader.get(serviceUrl, Example.class);
//
// Integer n = 1;
// assertEquals(object.getName(), "A");
// assertEquals(object.getN(), n);
// assertEquals(object.getReal(), true);
// }
//
// @Test
// public void whenGetJsonUrl_thenJsonObjectReturned() throws Exception {
// JSONObject jsonObject = JsonUrlReader.getJson(serviceUrl);
//
// assertEquals(jsonObject.getString("name"), "A");
// assertEquals(jsonObject.getInt("n"), 1);
// assertEquals(jsonObject.getBoolean("real"), true);
// }
//}

View File

@ -24,7 +24,7 @@ public class JacksonCollectionDeserializationUnitTest {
final ObjectMapper mapper = new ObjectMapper();
final List<MyDto> listOfDtos = Lists.newArrayList(new MyDto("a", 1, true), new MyDto("bc", 3, false));
listOfDtos
final String jsonArray = mapper.writeValueAsString(listOfDtos);
// [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}]

View File

@ -1,2 +1,2 @@
## Relevant Articles
- [Guide to Java Jackson-jr Library](https://www.baeldung.com/java-jackson-jr-library)
## 相关文章
- [Java Jackson-jr 库使用介绍](https://track.ossez.com/articles/PL-A-37491628/Java-Jackson-jr?edit=true

View File

@ -8,9 +8,9 @@
<name>jackson-jr</name>
<parent>
<groupId>com.baeldung</groupId>
<groupId>com.ossez</groupId>
<artifactId>jackson-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<version>0.0.2-SNAPSHOT</version>
</parent>
<dependencies>

View File

@ -21,9 +21,15 @@
<module>jackson-conversions-2</module>
<module>jackson-custom-conversions</module>
<module>jackson-exceptions</module>
<module>jackson-jr</module>
</modules>
<dependencies>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>${jakarta.persistence.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>

View File

@ -43,7 +43,7 @@
<module>core-java-modules</module>
<module>image-compressing</module>
<module>image-processing</module>
<!-- <module>jackson-modules</module>-->
<module>jackson-modules</module>
<!-- <module>jackson-simple</module>-->
<!-- <module>parent-java</module>-->
<module>parent-boot-2</module>
@ -86,6 +86,7 @@
<fastutil.version>5.0.9</fastutil.version>
<!-- Hibernate / JPA -->
<jakarta.persistence.version>3.2.0-M2</jakarta.persistence.version>
<hibernate.version>4.3.5.Final</hibernate.version>
<!-- Bean validation -->