minor formatting cleanup
This commit is contained in:
+7
-5
@@ -47,9 +47,10 @@ public class ExtraAnnotationUnitTest {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation");
|
||||
ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class).withAttribute("version", "1.0");
|
||||
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")));
|
||||
}
|
||||
@@ -59,9 +60,10 @@ public class ExtraAnnotationUnitTest {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation");
|
||||
ObjectWriter writer = mapper.writerFor(BeanWithAppend.class).withAttribute("version", "1.0");
|
||||
ObjectWriter writer = mapper.writerFor(BeanWithAppend.class)
|
||||
.withAttribute("version", "1.0");
|
||||
String jsonString = writer.writeValueAsString(bean);
|
||||
|
||||
|
||||
assertThat(jsonString, containsString("version"));
|
||||
assertThat(jsonString, containsString("1.0"));
|
||||
}
|
||||
@@ -71,7 +73,7 @@ public class ExtraAnnotationUnitTest {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
NamingBean bean = new NamingBean(3, "Naming Bean");
|
||||
String jsonString = mapper.writeValueAsString(bean);
|
||||
|
||||
|
||||
assertThat(jsonString, containsString("bean_name"));
|
||||
}
|
||||
|
||||
|
||||
+1
-2
@@ -4,7 +4,6 @@ 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 {
|
||||
@@ -32,7 +31,7 @@ public class IdentityReferenceBeans {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
|
||||
@JsonIdentityReference(alwaysAsId = true)
|
||||
public static class BeanWithIdentityReference {
|
||||
|
||||
@@ -20,6 +20,7 @@ public class CustomListSerializer extends StdSerializer<List<ItemWithSerializer>
|
||||
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>();
|
||||
|
||||
@@ -11,7 +11,6 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
|
||||
|
||||
|
||||
private static final long serialVersionUID = -7449444168934819290L;
|
||||
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
|
||||
|
||||
|
||||
@@ -28,9 +28,11 @@ public class ItemDeserializer extends StdDeserializer<Item> {
|
||||
*/
|
||||
@Override
|
||||
public Item deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
|
||||
final JsonNode node = jp.getCodec().readTree(jp);
|
||||
final JsonNode node = jp.getCodec()
|
||||
.readTree(jp);
|
||||
final int id = (Integer) ((IntNode) node.get("id")).numberValue();
|
||||
final String itemName = node.get("itemName").asText();
|
||||
final String itemName = node.get("itemName")
|
||||
.asText();
|
||||
final int userId = (Integer) ((IntNode) node.get("createdBy")).numberValue();
|
||||
|
||||
return new Item(id, itemName, new User(userId, null));
|
||||
|
||||
+4
-2
@@ -28,9 +28,11 @@ public class ItemDeserializerOnClass extends StdDeserializer<ItemWithSerializer>
|
||||
*/
|
||||
@Override
|
||||
public ItemWithSerializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
|
||||
final JsonNode node = jp.getCodec().readTree(jp);
|
||||
final JsonNode node = jp.getCodec()
|
||||
.readTree(jp);
|
||||
final int id = (Integer) ((IntNode) node.get("id")).numberValue();
|
||||
final String itemName = node.get("itemName").asText();
|
||||
final String itemName = node.get("itemName")
|
||||
.asText();
|
||||
final int userId = (Integer) ((IntNode) node.get("owner")).numberValue();
|
||||
|
||||
return new ItemWithSerializer(id, itemName, new User(userId, null));
|
||||
|
||||
+30
-35
@@ -16,54 +16,49 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class JacksonMapDeserializeUnitTest {
|
||||
|
||||
private Map<MyPair, String> map;
|
||||
private Map<MyPair, MyPair> cmap;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
private Map<MyPair, String> map;
|
||||
private Map<MyPair, MyPair> cmap;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
public void whenSimpleMapDeserialize_thenCorrect()
|
||||
throws JsonParseException, JsonMappingException, IOException {
|
||||
@Test
|
||||
public void whenSimpleMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
|
||||
final String jsonInput = "{\"key\": \"value\"}";
|
||||
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
|
||||
};
|
||||
final String jsonInput = "{\"key\": \"value\"}";
|
||||
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
|
||||
};
|
||||
|
||||
final Map<String, String> map = mapper.readValue(jsonInput, typeRef);
|
||||
final Map<String, String> map = mapper.readValue(jsonInput, typeRef);
|
||||
|
||||
Assert.assertEquals("value", map.get("key"));
|
||||
}
|
||||
Assert.assertEquals("value", map.get("key"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenObjectStringMapDeserialize_thenCorrect()
|
||||
throws JsonParseException, JsonMappingException, IOException {
|
||||
@Test
|
||||
public void whenObjectStringMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
|
||||
final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}";
|
||||
final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}";
|
||||
|
||||
TypeReference<HashMap<MyPair, String>> typeRef = new TypeReference<HashMap<MyPair, String>>() {
|
||||
};
|
||||
TypeReference<HashMap<MyPair, String>> typeRef = new TypeReference<HashMap<MyPair, String>>() {
|
||||
};
|
||||
|
||||
map = mapper.readValue(jsonInput, typeRef);
|
||||
map = mapper.readValue(jsonInput, typeRef);
|
||||
|
||||
Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello")));
|
||||
Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello")));
|
||||
|
||||
ClassWithAMap classWithMap = mapper.readValue(jsonInput,
|
||||
ClassWithAMap.class);
|
||||
ClassWithAMap classWithMap = mapper.readValue(jsonInput, ClassWithAMap.class);
|
||||
|
||||
Assert.assertEquals("Comedy",
|
||||
classWithMap.getMap().get(new MyPair("Abbott", "Costello")));
|
||||
}
|
||||
Assert.assertEquals("Comedy", classWithMap.getMap()
|
||||
.get(new MyPair("Abbott", "Costello")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenObjectObjectMapDeserialize_thenCorrect()
|
||||
throws JsonParseException, JsonMappingException, IOException {
|
||||
@Test
|
||||
public void whenObjectObjectMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
|
||||
final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}";
|
||||
TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() {
|
||||
};
|
||||
final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}";
|
||||
TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() {
|
||||
};
|
||||
|
||||
cmap = mapper.readValue(jsonInput, typeRef);
|
||||
cmap = mapper.readValue(jsonInput, typeRef);
|
||||
|
||||
Assert.assertEquals(new MyPair("Comedy", "1940s"),
|
||||
cmap.get(new MyPair("Abbott", "Costello")));
|
||||
}
|
||||
Assert.assertEquals(new MyPair("Comedy", "1940s"), cmap.get(new MyPair("Abbott", "Costello")));
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -27,7 +27,9 @@ public class JacksonInjectUnitTest {
|
||||
|
||||
// act
|
||||
InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id);
|
||||
Author author = new ObjectMapper().reader(inject).forType(Author.class).readValue(authorJson);
|
||||
Author author = new ObjectMapper().reader(inject)
|
||||
.forType(Author.class)
|
||||
.readValue(authorJson);
|
||||
|
||||
// assert
|
||||
assertThat(author.getId()).isEqualTo(id);
|
||||
|
||||
+20
-7
@@ -23,15 +23,28 @@ public class JsonAnySetterUnitTest {
|
||||
String json = "{\"USA\":10.00,\"UK\":15.00,\"China\":23.00,\"Brazil\":12.00,\"France\":8.00,\"Russia\":18.00}";
|
||||
|
||||
// act
|
||||
Inventory inventory = new ObjectMapper().readerFor(Inventory.class).readValue(json);
|
||||
Inventory inventory = new ObjectMapper().readerFor(Inventory.class)
|
||||
.readValue(json);
|
||||
|
||||
// assert
|
||||
assertThat(from(json).getMap(".").get("USA")).isEqualTo(inventory.getCountryDeliveryCost().get("USA"));
|
||||
assertThat(from(json).getMap(".").get("UK")).isEqualTo(inventory.getCountryDeliveryCost().get("UK"));
|
||||
assertThat(from(json).getMap(".").get("China")).isEqualTo(inventory.getCountryDeliveryCost().get("China"));
|
||||
assertThat(from(json).getMap(".").get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost().get("Brazil"));
|
||||
assertThat(from(json).getMap(".").get("France")).isEqualTo(inventory.getCountryDeliveryCost().get("France"));
|
||||
assertThat(from(json).getMap(".").get("Russia")).isEqualTo(inventory.getCountryDeliveryCost().get("Russia"));
|
||||
assertThat(from(json).getMap(".")
|
||||
.get("USA")).isEqualTo(inventory.getCountryDeliveryCost()
|
||||
.get("USA"));
|
||||
assertThat(from(json).getMap(".")
|
||||
.get("UK")).isEqualTo(inventory.getCountryDeliveryCost()
|
||||
.get("UK"));
|
||||
assertThat(from(json).getMap(".")
|
||||
.get("China")).isEqualTo(inventory.getCountryDeliveryCost()
|
||||
.get("China"));
|
||||
assertThat(from(json).getMap(".")
|
||||
.get("Brazil")).isEqualTo(inventory.getCountryDeliveryCost()
|
||||
.get("Brazil"));
|
||||
assertThat(from(json).getMap(".")
|
||||
.get("France")).isEqualTo(inventory.getCountryDeliveryCost()
|
||||
.get("France"));
|
||||
assertThat(from(json).getMap(".")
|
||||
.get("Russia")).isEqualTo(inventory.getCountryDeliveryCost()
|
||||
.get("Russia"));
|
||||
|
||||
}
|
||||
}
|
||||
+3
-6
@@ -20,14 +20,11 @@ public class JsonCreatorUnitTest {
|
||||
public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException {
|
||||
|
||||
// arrange
|
||||
String authorJson =
|
||||
"{" +
|
||||
" \"christianName\": \"Alex\"," +
|
||||
" \"surname\": \"Theedom\"" +
|
||||
"}";
|
||||
String authorJson = "{" + " \"christianName\": \"Alex\"," + " \"surname\": \"Theedom\"" + "}";
|
||||
|
||||
// act
|
||||
final Author author = new ObjectMapper().readerFor(Author.class).readValue(authorJson);
|
||||
final Author author = new ObjectMapper().readerFor(Author.class)
|
||||
.readValue(authorJson);
|
||||
|
||||
// assert
|
||||
assertThat(from(authorJson).getString("christianName")).isEqualTo(author.getFirstName());
|
||||
|
||||
+2
-1
@@ -24,7 +24,8 @@ public class JsonDeserializeUnitTest {
|
||||
String bookJson = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"title\":\"Effective Java\",\"authors\":[{\"id\":\"9bcd817d-0141-42e6-8f04-e5aaab0980b6\",\"firstName\":\"Joshua\",\"lastName\":\"Bloch\"}],\"price\":0,\"published\":\"25-12-2017 13:30:25\",\"pages\":null,\"isbn\":null}";
|
||||
|
||||
// act
|
||||
Book book = new ObjectMapper().readerFor(Book.class).readValue(bookJson);
|
||||
Book book = new ObjectMapper().readerFor(Book.class)
|
||||
.readValue(bookJson);
|
||||
|
||||
// assert
|
||||
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
|
||||
|
||||
+5
-2
@@ -23,10 +23,13 @@ public class JsonSetterUnitTest {
|
||||
String json = "{\"firstName\":\"Alex\",\"lastName\":\"Theedom\",\"publications\":[{\"title\":\"Professional Java EE Design Patterns\"}]}";
|
||||
|
||||
// act
|
||||
Author author = new ObjectMapper().readerFor(Author.class).readValue(json);
|
||||
Author author = new ObjectMapper().readerFor(Author.class)
|
||||
.readValue(json);
|
||||
|
||||
// assert
|
||||
assertThat(from(json).getList("publications").size()).isEqualTo(author.getItems().size());
|
||||
assertThat(from(json).getList("publications")
|
||||
.size()).isEqualTo(author.getItems()
|
||||
.size());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.baeldung.jackson.dynamicIgnore;
|
||||
|
||||
|
||||
public class Address implements Hidable {
|
||||
private String city;
|
||||
private String country;
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.baeldung.jackson.dynamicIgnore;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
|
||||
@JsonIgnoreProperties("hidden")
|
||||
public interface Hidable {
|
||||
boolean isHidden();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.baeldung.jackson.dynamicIgnore;
|
||||
|
||||
|
||||
public class Person implements Hidable {
|
||||
private String name;
|
||||
private Address address;
|
||||
@@ -13,7 +12,6 @@ public class Person implements Hidable {
|
||||
this.hidden = hidden;
|
||||
}
|
||||
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
@@ -29,6 +27,7 @@ public class Person implements Hidable {
|
||||
public void setAddress(final Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHidden() {
|
||||
return hidden;
|
||||
|
||||
@@ -22,18 +22,16 @@ public class JsonFormatUnitTest {
|
||||
@Test
|
||||
public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingException {
|
||||
|
||||
User user = new User("Jay", "Sridhar");
|
||||
User user = new User("Jay", "Sridhar");
|
||||
|
||||
String result = new ObjectMapper().writeValueAsString(user);
|
||||
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 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));
|
||||
// Expected to be close to current time
|
||||
long now = new Date().getTime();
|
||||
assertThat(from(result).getLong("dateNum")).isCloseTo(now, withPercentage(10.0));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -23,11 +23,11 @@ public class JsonFilterUnitTest {
|
||||
|
||||
// arrange
|
||||
Author author = new Author("Alex", "Theedom");
|
||||
FilterProvider filters = new SimpleFilterProvider()
|
||||
.addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName"));
|
||||
FilterProvider filters = new SimpleFilterProvider().addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName"));
|
||||
|
||||
// act
|
||||
String result = new ObjectMapper().writer(filters).writeValueAsString(author);
|
||||
String result = new ObjectMapper().writer(filters)
|
||||
.writeValueAsString(author);
|
||||
|
||||
// assert
|
||||
assertThat(from(result).getList("items")).isNull();
|
||||
|
||||
@@ -17,9 +17,7 @@ public class Book extends Item {
|
||||
|
||||
private String ISBN;
|
||||
|
||||
@JsonFormat(
|
||||
shape = JsonFormat.Shape.STRING,
|
||||
pattern = "dd-MM-yyyy HH:mm:ss")
|
||||
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
|
||||
private Date published;
|
||||
private BigDecimal pages;
|
||||
|
||||
|
||||
+1
-4
@@ -31,10 +31,7 @@ public class JsonFormatUnitTest {
|
||||
String toParse = "20-12-2014 14:30:00";
|
||||
Date date = df.parse(toParse);
|
||||
|
||||
Book book = new Book(
|
||||
"Design Patterns: Elements of Reusable Object-oriented Software",
|
||||
new Author("The", "GoF")
|
||||
);
|
||||
Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF"));
|
||||
book.setPublished(date);
|
||||
|
||||
// act
|
||||
|
||||
@@ -12,9 +12,7 @@ import java.util.List;
|
||||
* @author Alex Theedom www.readlearncode.com
|
||||
* @version 1.0
|
||||
*/
|
||||
@JsonIdentityInfo(
|
||||
generator = ObjectIdGenerators.PropertyGenerator.class,
|
||||
property = "id")
|
||||
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
|
||||
public class Author extends Person {
|
||||
|
||||
private List<Item> items = new ArrayList<>();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.baeldung.jackson.general.jsonidentityinfo;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -11,7 +10,9 @@ import java.util.List;
|
||||
*/
|
||||
public class Course extends Item {
|
||||
|
||||
public enum Medium {CLASSROOM, ONLINE}
|
||||
public enum Medium {
|
||||
CLASSROOM, ONLINE
|
||||
}
|
||||
|
||||
public enum Level {
|
||||
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
||||
|
||||
@@ -13,9 +13,7 @@ import java.util.UUID;
|
||||
* @author Alex Theedom www.readlearncode.com
|
||||
* @version 1.0
|
||||
*/
|
||||
@JsonIdentityInfo(
|
||||
generator = ObjectIdGenerators.PropertyGenerator.class,
|
||||
property = "id")
|
||||
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
|
||||
public class Item {
|
||||
|
||||
private UUID id;
|
||||
@@ -23,7 +21,8 @@ public class Item {
|
||||
private List<Person> authors = new ArrayList<>();
|
||||
private float price;
|
||||
|
||||
public Item(){}
|
||||
public Item() {
|
||||
}
|
||||
|
||||
public Item(String title, Author author) {
|
||||
this.id = UUID.randomUUID();
|
||||
|
||||
@@ -14,7 +14,8 @@ public class Person {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public Person(){}
|
||||
public Person() {
|
||||
}
|
||||
|
||||
public Person(String firstName, String lastName) {
|
||||
this.id = UUID.randomUUID();
|
||||
|
||||
@@ -19,7 +19,8 @@ public class Item {
|
||||
private List<Person> authors = new ArrayList<>();
|
||||
private float price;
|
||||
|
||||
public Item(){}
|
||||
public Item() {
|
||||
}
|
||||
|
||||
public Item(String title, Author author) {
|
||||
this.id = UUID.randomUUID();
|
||||
|
||||
+3
-6
@@ -21,10 +21,7 @@ public class JsonPropertyUnitTest {
|
||||
public void whenSerializingUsingJsonProperty_thenCorrect() throws JsonProcessingException {
|
||||
|
||||
// arrange
|
||||
Book book = new Book(
|
||||
"Design Patterns: Elements of Reusable Object-oriented Software",
|
||||
new Author("The", "GoF")
|
||||
);
|
||||
Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF"));
|
||||
book.configureBinding("Hardback");
|
||||
|
||||
// act
|
||||
@@ -62,12 +59,12 @@ public class JsonPropertyUnitTest {
|
||||
String result = "{\"id\":\"cd941587-d1ae-4c2a-9a36-29533bf50411\",\"title\":\"Design Patterns: Elements of Reusable Object-oriented Software\",\"authors\":[{\"id\":\"c8e26318-2f5b-4fa2-9fdc-6e99be021fca\",\"firstName\":\"The\",\"lastName\":\"GoF\"}],\"binding\":\"Hardback\"}";
|
||||
|
||||
// act
|
||||
Book book = new ObjectMapper().readerFor(Book.class).readValue(result);
|
||||
Book book = new ObjectMapper().readerFor(Book.class)
|
||||
.readValue(result);
|
||||
|
||||
// assert
|
||||
assertThat(book.coverBinding()).isEqualTo("Hardback");
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
-1
@@ -1,6 +1,5 @@
|
||||
package com.baeldung.jackson.general.jsonunwrapped;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -22,7 +22,8 @@ public class JsonViewUnitTest {
|
||||
Order order = new Order(120);
|
||||
|
||||
// act
|
||||
String result = new ObjectMapper().writerWithView(Views.Internal.class).writeValueAsString(order);
|
||||
String result = new ObjectMapper().writerWithView(Views.Internal.class)
|
||||
.writeValueAsString(order);
|
||||
|
||||
// assert
|
||||
assertThat(from(result).getUUID("id")).isNotNull();
|
||||
@@ -49,7 +50,8 @@ public class JsonViewUnitTest {
|
||||
Order order = new Order(120);
|
||||
|
||||
// act
|
||||
String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(order);
|
||||
String result = new ObjectMapper().writerWithView(Views.Public.class)
|
||||
.writeValueAsString(order);
|
||||
|
||||
// assert
|
||||
assertThat(from(result).getUUID("id")).isNotNull();
|
||||
@@ -68,5 +70,4 @@ public class JsonViewUnitTest {
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.baeldung.jackson.general.reference;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -11,7 +10,9 @@ import java.util.List;
|
||||
*/
|
||||
public class Course extends Item {
|
||||
|
||||
public enum Medium {CLASSROOM, ONLINE}
|
||||
public enum Medium {
|
||||
CLASSROOM, ONLINE
|
||||
}
|
||||
|
||||
public enum Level {
|
||||
BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3);
|
||||
|
||||
@@ -21,7 +21,8 @@ public class Item {
|
||||
private List<Person> authors = new ArrayList<>();
|
||||
private float price;
|
||||
|
||||
public Item(){}
|
||||
public Item() {
|
||||
}
|
||||
|
||||
public Item(String title, Author author) {
|
||||
this.id = UUID.randomUUID();
|
||||
|
||||
@@ -14,7 +14,8 @@ public class Person {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public Person(){}
|
||||
public Person() {
|
||||
}
|
||||
|
||||
public Person(String firstName, String lastName) {
|
||||
this.id = UUID.randomUUID();
|
||||
|
||||
@@ -36,7 +36,7 @@ public class ReferenceUnitTest {
|
||||
/*
|
||||
Without references defined it throws StackOverflowError.
|
||||
Authors excluded.
|
||||
|
||||
|
||||
{
|
||||
"id": "9c45d9b3-4888-4c24-8b74-65ef35627cd7",
|
||||
"firstName": "Alex",
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ public class JsonAutoDetectUnitTest {
|
||||
},
|
||||
"internalAudit": 1234567890
|
||||
}
|
||||
|
||||
|
||||
Without @JsonAutoDetect
|
||||
{
|
||||
"id": "c94774d9-de8f-4244-85d5-624bd3a4567a",
|
||||
|
||||
-1
@@ -28,7 +28,6 @@ public class JsonIncludeUnitTest {
|
||||
assertThat(from(result).getString("firstName")).isEqualTo("Alex");
|
||||
assertThat(result).doesNotContain("lastName");
|
||||
|
||||
|
||||
/*
|
||||
{
|
||||
"id": "e8bb4802-6e0c-4fa5-9f68-c233272399cd",
|
||||
|
||||
+6
-6
@@ -12,29 +12,29 @@ import static org.junit.Assert.assertTrue;
|
||||
public class ItemIdRemovedFromUserUnitTest {
|
||||
@Test
|
||||
public void givenRemoveItemJson_whenDeserialize_shouldHaveProperClassType() throws IOException {
|
||||
//given
|
||||
// given
|
||||
Event event = new ItemIdRemovedFromUser("1", 12345567L, "item_1", 2L);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
String eventJson = objectMapper.writeValueAsString(event);
|
||||
|
||||
//when
|
||||
// when
|
||||
Event result = new ObjectMapper().readValue(eventJson, Event.class);
|
||||
|
||||
//then
|
||||
// then
|
||||
assertTrue(result instanceof ItemIdRemovedFromUser);
|
||||
assertEquals("item_1", ((ItemIdRemovedFromUser) result).getItemId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAdddItemJson_whenSerialize_shouldIgnoreIdPropertyFromSuperclass() throws IOException {
|
||||
//given
|
||||
// given
|
||||
Event event = new ItemIdAddedToUser("1", 12345567L, "item_1", 2L);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
//when
|
||||
// when
|
||||
String eventJson = objectMapper.writeValueAsString(event);
|
||||
|
||||
//then
|
||||
// then
|
||||
assertFalse(eventJson.contains("id"));
|
||||
}
|
||||
|
||||
|
||||
@@ -21,12 +21,12 @@ public class SubTypeHandlingUnitTest {
|
||||
assertEquals("Mercedes-Benz", truck.getMake());
|
||||
assertEquals("S500", truck.getModel());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException{
|
||||
public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.enableDefaultTyping();
|
||||
|
||||
|
||||
SubTypeConstructorStructure.Car car = new SubTypeConstructorStructure.Car("Mercedes-Benz", "S500", 5, 250.0);
|
||||
SubTypeConstructorStructure.Truck truck = new SubTypeConstructorStructure.Truck("Isuzu", "NQR", 7500.0);
|
||||
|
||||
|
||||
+8
-4
@@ -30,8 +30,10 @@ public class TypeInfoInclusionUnitTest {
|
||||
String jsonDataString = mapper.writeValueAsString(serializedFleet);
|
||||
TypeInfoStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoStructure.Fleet.class);
|
||||
|
||||
assertThat(deserializedFleet.getVehicles().get(0), instanceOf(TypeInfoStructure.Car.class));
|
||||
assertThat(deserializedFleet.getVehicles().get(1), instanceOf(TypeInfoStructure.Truck.class));
|
||||
assertThat(deserializedFleet.getVehicles()
|
||||
.get(0), instanceOf(TypeInfoStructure.Car.class));
|
||||
assertThat(deserializedFleet.getVehicles()
|
||||
.get(1), instanceOf(TypeInfoStructure.Truck.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -51,7 +53,9 @@ public class TypeInfoInclusionUnitTest {
|
||||
String jsonDataString = mapper.writeValueAsString(serializedFleet);
|
||||
TypeInfoAnnotatedStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoAnnotatedStructure.Fleet.class);
|
||||
|
||||
assertThat(deserializedFleet.getVehicles().get(0), instanceOf(TypeInfoAnnotatedStructure.Car.class));
|
||||
assertThat(deserializedFleet.getVehicles().get(1), instanceOf(TypeInfoAnnotatedStructure.Truck.class));
|
||||
assertThat(deserializedFleet.getVehicles()
|
||||
.get(0), instanceOf(TypeInfoAnnotatedStructure.Car.class));
|
||||
assertThat(deserializedFleet.getVehicles()
|
||||
.get(1), instanceOf(TypeInfoAnnotatedStructure.Truck.class));
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,8 @@ public class ExampleStructure {
|
||||
private static ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
static JsonNode getExampleRoot() throws IOException {
|
||||
InputStream exampleInput = ExampleStructure.class.getClassLoader().getResourceAsStream("node_example.json");
|
||||
InputStream exampleInput = ExampleStructure.class.getClassLoader()
|
||||
.getResourceAsStream("node_example.json");
|
||||
JsonNode rootNode = mapper.readTree(exampleInput);
|
||||
return rootNode;
|
||||
}
|
||||
|
||||
@@ -28,8 +28,10 @@ public class NodeOperationUnitTest {
|
||||
|
||||
final JsonNode node = mapper.valueToTree(fromValue);
|
||||
|
||||
assertEquals(2016, node.get("id").intValue());
|
||||
assertEquals("baeldung.com", node.get("name").textValue());
|
||||
assertEquals(2016, node.get("id")
|
||||
.intValue());
|
||||
assertEquals("baeldung.com", node.get("name")
|
||||
.textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -72,12 +74,21 @@ public class NodeOperationUnitTest {
|
||||
public void givenANode_whenAddingIntoATree_thenCorrect() throws IOException {
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
final ObjectNode addedNode = ((ObjectNode) rootNode).putObject("address");
|
||||
addedNode.put("city", "Seattle").put("state", "Washington").put("country", "United States");
|
||||
addedNode.put("city", "Seattle")
|
||||
.put("state", "Washington")
|
||||
.put("country", "United States");
|
||||
|
||||
assertFalse(rootNode.path("address").isMissingNode());
|
||||
assertEquals("Seattle", rootNode.path("address").path("city").textValue());
|
||||
assertEquals("Washington", rootNode.path("address").path("state").textValue());
|
||||
assertEquals("United States", rootNode.path("address").path("country").textValue());
|
||||
assertFalse(rootNode.path("address")
|
||||
.isMissingNode());
|
||||
assertEquals("Seattle", rootNode.path("address")
|
||||
.path("city")
|
||||
.textValue());
|
||||
assertEquals("Washington", rootNode.path("address")
|
||||
.path("state")
|
||||
.textValue());
|
||||
assertEquals("United States", rootNode.path("address")
|
||||
.path("country")
|
||||
.textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -88,8 +99,12 @@ public class NodeOperationUnitTest {
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
((ObjectNode) rootNode).set("name", newNode);
|
||||
|
||||
assertFalse(rootNode.path("name").path("nick").isMissingNode());
|
||||
assertEquals("cowtowncoder", rootNode.path("name").path("nick").textValue());
|
||||
assertFalse(rootNode.path("name")
|
||||
.path("nick")
|
||||
.isMissingNode());
|
||||
assertEquals("cowtowncoder", rootNode.path("name")
|
||||
.path("nick")
|
||||
.textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -97,7 +112,8 @@ public class NodeOperationUnitTest {
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
((ObjectNode) rootNode).remove("company");
|
||||
|
||||
assertTrue(rootNode.path("company").isMissingNode());
|
||||
assertTrue(rootNode.path("company")
|
||||
.isMissingNode());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -25,8 +25,6 @@ public class CustomCarDeserializer extends StdDeserializer<Car> {
|
||||
super(vc);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public Car deserialize(final JsonParser parser, final DeserializationContext deserializer) throws IOException {
|
||||
final Car car = new Car();
|
||||
|
||||
@@ -8,8 +8,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class CustomCarSerializer extends StdSerializer<Car>
|
||||
{
|
||||
public class CustomCarSerializer extends StdSerializer<Car> {
|
||||
|
||||
private static final long serialVersionUID = 1396140685442227917L;
|
||||
|
||||
@@ -22,8 +21,7 @@ public class CustomCarSerializer extends StdSerializer<Car>
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException
|
||||
{
|
||||
public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException {
|
||||
jsonGenerator.writeStartObject();
|
||||
jsonGenerator.writeStringField("model: ", car.getType());
|
||||
jsonGenerator.writeEndObject();
|
||||
|
||||
+2
-1
@@ -40,7 +40,8 @@ public class JavaReadWriteJsonExampleUnitTest {
|
||||
final ObjectMapper objectMapper = new ObjectMapper();
|
||||
final JsonNode jsonNode = objectMapper.readTree(EXAMPLE_JSON);
|
||||
assertNotNull(jsonNode);
|
||||
assertThat(jsonNode.get("color").asText(), containsString("Black"));
|
||||
assertThat(jsonNode.get("color")
|
||||
.asText(), containsString("Black"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class SerializationDeserializationFeatureUnitTest {
|
||||
public class SerializationDeserializationFeatureUnitTest {
|
||||
final String EXAMPLE_JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
|
||||
final String JSON_CAR = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }";
|
||||
final String JSON_ARRAY = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"BMW\" }]";
|
||||
|
||||
@@ -53,12 +53,14 @@ public class PolymorphismUnitTest {
|
||||
String orderJson = "{\"type\":{\"ordertype\":\"internal\",\"id\":100,\"name\":\"directors\"}}";
|
||||
|
||||
// act
|
||||
Order order = new ObjectMapper().readerFor(Order.class).readValue(orderJson);
|
||||
Order order = new ObjectMapper().readerFor(Order.class)
|
||||
.readValue(orderJson);
|
||||
|
||||
// assert
|
||||
// assert
|
||||
assertThat(from(orderJson).getString("type.ordertype")).isEqualTo("internal");
|
||||
assertThat(((Order.InternalType) order.getType()).name).isEqualTo("directors");
|
||||
assertThat(((Order.InternalType) order.getType()).id).isEqualTo(100);
|
||||
assertThat(order.getType().getClass()).isEqualTo(Order.InternalType.class);
|
||||
assertThat(order.getType()
|
||||
.getClass()).isEqualTo(Order.InternalType.class);
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,8 @@ public class JacksonPrettyPrintUnitTest {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
try {
|
||||
final Object json = mapper.readValue(readFile(fileName, StandardCharsets.UTF_8), Object.class);
|
||||
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
|
||||
System.out.println(mapper.writerWithDefaultPrettyPrinter()
|
||||
.writeValueAsString(json));
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
@@ -42,7 +43,8 @@ public class JacksonPrettyPrintUnitTest {
|
||||
|
||||
static String readFile(final String path, final Charset encoding) throws IOException {
|
||||
final byte[] encoded = Files.readAllBytes(Paths.get(path));
|
||||
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
|
||||
return encoding.decode(ByteBuffer.wrap(encoded))
|
||||
.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -17,7 +17,10 @@ public class SandboxUnitTest {
|
||||
testElement.setX(10);
|
||||
testElement.setY("adasd");
|
||||
final ObjectMapper om = new ObjectMapper();
|
||||
om.setVisibility(om.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE));
|
||||
om.setVisibility(om.getSerializationConfig()
|
||||
.getDefaultVisibilityChecker()
|
||||
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
|
||||
.withGetterVisibility(JsonAutoDetect.Visibility.NONE));
|
||||
|
||||
final String serialized = om.writeValueAsString(testElement);
|
||||
System.err.println(serialized);
|
||||
|
||||
+33
-37
@@ -14,57 +14,53 @@ import com.fasterxml.jackson.databind.ser.std.MapSerializer;
|
||||
|
||||
public class JacksonMapSerializeUnitTest {
|
||||
|
||||
@JsonSerialize(keyUsing = MyPairSerializer.class)
|
||||
private Map<MyPair, String> map;
|
||||
@JsonSerialize(keyUsing = MyPairSerializer.class)
|
||||
private Map<MyPair, String> map;
|
||||
|
||||
@JsonSerialize(keyUsing = MapSerializer.class)
|
||||
private Map<MyPair, MyPair> cmap;
|
||||
@JsonSerialize(keyUsing = MapSerializer.class)
|
||||
private Map<MyPair, MyPair> cmap;
|
||||
|
||||
@JsonSerialize(keyUsing = MyPairSerializer.class)
|
||||
private MyPair mapKey;
|
||||
@JsonSerialize(keyUsing = MyPairSerializer.class)
|
||||
private MyPair mapKey;
|
||||
|
||||
@JsonSerialize(keyUsing = MyPairSerializer.class)
|
||||
private MyPair mapValue;
|
||||
@JsonSerialize(keyUsing = MyPairSerializer.class)
|
||||
private MyPair mapValue;
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
public void whenSimpleMapSerialize_thenCorrect()
|
||||
throws JsonProcessingException {
|
||||
@Test
|
||||
public void whenSimpleMapSerialize_thenCorrect() throws JsonProcessingException {
|
||||
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key", "value");
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key", "value");
|
||||
|
||||
final String jsonResult = mapper.writeValueAsString(map);
|
||||
final String jsonResult = mapper.writeValueAsString(map);
|
||||
|
||||
Assert.assertEquals("{\"key\":\"value\"}", jsonResult);
|
||||
}
|
||||
Assert.assertEquals("{\"key\":\"value\"}", jsonResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomObjectStringMapSerialize_thenCorrect()
|
||||
throws JsonProcessingException {
|
||||
@Test
|
||||
public void whenCustomObjectStringMapSerialize_thenCorrect() throws JsonProcessingException {
|
||||
|
||||
map = new HashMap<>();
|
||||
MyPair key = new MyPair("Abbott", "Costello");
|
||||
map.put(key, "Comedy");
|
||||
map = new HashMap<>();
|
||||
MyPair key = new MyPair("Abbott", "Costello");
|
||||
map.put(key, "Comedy");
|
||||
|
||||
final String jsonResult = mapper.writeValueAsString(map);
|
||||
final String jsonResult = mapper.writeValueAsString(map);
|
||||
|
||||
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult);
|
||||
}
|
||||
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomObjectObjectMapSerialize_thenCorrect()
|
||||
throws JsonProcessingException {
|
||||
@Test
|
||||
public void whenCustomObjectObjectMapSerialize_thenCorrect() throws JsonProcessingException {
|
||||
|
||||
cmap = new HashMap<>();
|
||||
mapKey = new MyPair("Abbott", "Costello");
|
||||
mapValue = new MyPair("Comedy", "1940's");
|
||||
cmap.put(mapKey, mapValue);
|
||||
cmap = new HashMap<>();
|
||||
mapKey = new MyPair("Abbott", "Costello");
|
||||
mapValue = new MyPair("Comedy", "1940's");
|
||||
cmap.put(mapKey, mapValue);
|
||||
|
||||
final String jsonResult = mapper.writeValueAsString(cmap);
|
||||
final String jsonResult = mapper.writeValueAsString(cmap);
|
||||
|
||||
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}",
|
||||
jsonResult);
|
||||
}
|
||||
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}", jsonResult);
|
||||
}
|
||||
}
|
||||
|
||||
+5
-2
@@ -48,10 +48,13 @@ public class JacksonSerializeUnitTest {
|
||||
module.addSerializer(new ActorJacksonSerializer(ActorJackson.class));
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final String jsonResult = mapper.registerModule(module).writer(new DefaultPrettyPrinter()).writeValueAsString(movieWithNullValue);
|
||||
final String jsonResult = mapper.registerModule(module)
|
||||
.writer(new DefaultPrettyPrinter())
|
||||
.writeValueAsString(movieWithNullValue);
|
||||
|
||||
final Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class);
|
||||
final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(json);
|
||||
final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
|
||||
.writeValueAsString(json);
|
||||
|
||||
Assert.assertEquals(jsonResult, expectedOutput);
|
||||
}
|
||||
|
||||
-1
@@ -28,7 +28,6 @@ public class JsonRawValueUnitTest {
|
||||
// assert
|
||||
assertThat(result.contains(customerConfig));
|
||||
|
||||
|
||||
/*
|
||||
{
|
||||
"firstName": "Alex",
|
||||
|
||||
+9
-10
@@ -1,6 +1,5 @@
|
||||
package com.baeldung.jackson.streaming;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.core.*;
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -18,12 +17,12 @@ public class JacksonStreamingAPIUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenJsonGenerator_whenAppendJsonToIt_thenGenerateJson() throws IOException {
|
||||
//given
|
||||
// given
|
||||
ByteArrayOutputStream stream = new ByteArrayOutputStream();
|
||||
JsonFactory jfactory = new JsonFactory();
|
||||
JsonGenerator jGenerator = jfactory.createGenerator(stream, JsonEncoding.UTF8);
|
||||
|
||||
//when
|
||||
// when
|
||||
jGenerator.writeStartObject();
|
||||
jGenerator.writeStringField("name", "Tom");
|
||||
jGenerator.writeNumberField("age", 25);
|
||||
@@ -35,14 +34,14 @@ public class JacksonStreamingAPIUnitTest {
|
||||
jGenerator.writeEndObject();
|
||||
jGenerator.close();
|
||||
|
||||
//then
|
||||
// then
|
||||
String json = new String(stream.toByteArray(), "UTF-8");
|
||||
assertEquals(json, "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJson_whenReadItUsingStreamAPI_thenShouldCreateProperJsonObject() throws IOException {
|
||||
//given
|
||||
// given
|
||||
String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}";
|
||||
JsonFactory jfactory = new JsonFactory();
|
||||
JsonParser jParser = jfactory.createParser(json);
|
||||
@@ -51,7 +50,7 @@ public class JacksonStreamingAPIUnitTest {
|
||||
Integer parsedAge = null;
|
||||
List<String> addresses = new LinkedList<>();
|
||||
|
||||
//when
|
||||
// when
|
||||
while (jParser.nextToken() != JsonToken.END_OBJECT) {
|
||||
|
||||
String fieldname = jParser.getCurrentName();
|
||||
@@ -78,7 +77,7 @@ public class JacksonStreamingAPIUnitTest {
|
||||
}
|
||||
jParser.close();
|
||||
|
||||
//then
|
||||
// then
|
||||
assertEquals(parsedName, "Tom");
|
||||
assertEquals(parsedAge, (Integer) 25);
|
||||
assertEquals(addresses, Arrays.asList("Poland", "5th avenue"));
|
||||
@@ -87,7 +86,7 @@ public class JacksonStreamingAPIUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenJson_whenWantToExtractPartOfIt_thenShouldExtractOnlyNeededFieldWithoutGoingThroughWholeJSON() throws IOException {
|
||||
//given
|
||||
// given
|
||||
String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}";
|
||||
JsonFactory jfactory = new JsonFactory();
|
||||
JsonParser jParser = jfactory.createParser(json);
|
||||
@@ -96,7 +95,7 @@ public class JacksonStreamingAPIUnitTest {
|
||||
Integer parsedAge = null;
|
||||
List<String> addresses = new LinkedList<>();
|
||||
|
||||
//when
|
||||
// when
|
||||
while (jParser.nextToken() != JsonToken.END_OBJECT) {
|
||||
|
||||
String fieldname = jParser.getCurrentName();
|
||||
@@ -110,7 +109,7 @@ public class JacksonStreamingAPIUnitTest {
|
||||
}
|
||||
jParser.close();
|
||||
|
||||
//then
|
||||
// then
|
||||
assertNull(parsedName);
|
||||
assertEquals(parsedAge, (Integer) 25);
|
||||
assertTrue(addresses.isEmpty());
|
||||
|
||||
@@ -124,7 +124,8 @@ public class JacksonAnnotationUnitTest {
|
||||
public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException {
|
||||
final String json = "{\"id\":1,\"theName\":\"My bean\"}";
|
||||
|
||||
final BeanWithCreator bean = new ObjectMapper().readerFor(BeanWithCreator.class).readValue(json);
|
||||
final BeanWithCreator bean = new ObjectMapper().readerFor(BeanWithCreator.class)
|
||||
.readValue(json);
|
||||
assertEquals("My bean", bean.name);
|
||||
}
|
||||
|
||||
@@ -133,7 +134,9 @@ public class JacksonAnnotationUnitTest {
|
||||
final String json = "{\"name\":\"My bean\"}";
|
||||
final InjectableValues inject = new InjectableValues.Std().addValue(int.class, 1);
|
||||
|
||||
final BeanWithInject bean = new ObjectMapper().reader(inject).forType(BeanWithInject.class).readValue(json);
|
||||
final BeanWithInject bean = new ObjectMapper().reader(inject)
|
||||
.forType(BeanWithInject.class)
|
||||
.readValue(json);
|
||||
assertEquals("My bean", bean.name);
|
||||
assertEquals(1, bean.id);
|
||||
}
|
||||
@@ -142,16 +145,19 @@ public class JacksonAnnotationUnitTest {
|
||||
public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws IOException {
|
||||
final String json = "{\"name\":\"My bean\",\"attr2\":\"val2\",\"attr1\":\"val1\"}";
|
||||
|
||||
final ExtendableBean bean = new ObjectMapper().readerFor(ExtendableBean.class).readValue(json);
|
||||
final ExtendableBean bean = new ObjectMapper().readerFor(ExtendableBean.class)
|
||||
.readValue(json);
|
||||
assertEquals("My bean", bean.name);
|
||||
assertEquals("val2", bean.getProperties().get("attr2"));
|
||||
assertEquals("val2", bean.getProperties()
|
||||
.get("attr2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeserializingUsingJsonSetter_thenCorrect() throws IOException {
|
||||
final String json = "{\"id\":1,\"name\":\"My bean\"}";
|
||||
|
||||
final BeanWithGetter bean = new ObjectMapper().readerFor(BeanWithGetter.class).readValue(json);
|
||||
final BeanWithGetter bean = new ObjectMapper().readerFor(BeanWithGetter.class)
|
||||
.readValue(json);
|
||||
assertEquals("My bean", bean.getTheName());
|
||||
}
|
||||
|
||||
@@ -161,7 +167,8 @@ public class JacksonAnnotationUnitTest {
|
||||
|
||||
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
|
||||
final EventWithSerializer event = new ObjectMapper().readerFor(EventWithSerializer.class).readValue(json);
|
||||
final EventWithSerializer event = new ObjectMapper().readerFor(EventWithSerializer.class)
|
||||
.readValue(json);
|
||||
assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
|
||||
}
|
||||
|
||||
@@ -232,7 +239,8 @@ public class JacksonAnnotationUnitTest {
|
||||
public void whenDeserializingPolymorphic_thenCorrect() throws IOException {
|
||||
final String json = "{\"animal\":{\"name\":\"lacy\",\"type\":\"cat\"}}";
|
||||
|
||||
final Zoo zoo = new ObjectMapper().readerFor(Zoo.class).readValue(json);
|
||||
final Zoo zoo = new ObjectMapper().readerFor(Zoo.class)
|
||||
.readValue(json);
|
||||
|
||||
assertEquals("lacy", zoo.animal.name);
|
||||
assertEquals(Zoo.Cat.class, zoo.animal.getClass());
|
||||
@@ -247,7 +255,8 @@ public class JacksonAnnotationUnitTest {
|
||||
assertThat(result, containsString("My bean"));
|
||||
assertThat(result, containsString("1"));
|
||||
|
||||
final BeanWithGetter resultBean = new ObjectMapper().readerFor(BeanWithGetter.class).readValue(result);
|
||||
final BeanWithGetter resultBean = new ObjectMapper().readerFor(BeanWithGetter.class)
|
||||
.readValue(result);
|
||||
assertEquals("My bean", resultBean.getTheName());
|
||||
}
|
||||
|
||||
@@ -278,7 +287,8 @@ public class JacksonAnnotationUnitTest {
|
||||
public void whenSerializingUsingJsonView_thenCorrect() throws JsonProcessingException, JsonProcessingException {
|
||||
final Item item = new Item(2, "book", "John");
|
||||
|
||||
final String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(item);
|
||||
final String result = new ObjectMapper().writerWithView(Views.Public.class)
|
||||
.writeValueAsString(item);
|
||||
|
||||
assertThat(result, containsString("book"));
|
||||
assertThat(result, containsString("2"));
|
||||
@@ -317,7 +327,8 @@ public class JacksonAnnotationUnitTest {
|
||||
|
||||
final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name"));
|
||||
|
||||
final String result = new ObjectMapper().writer(filters).writeValueAsString(bean);
|
||||
final String result = new ObjectMapper().writer(filters)
|
||||
.writeValueAsString(bean);
|
||||
|
||||
assertThat(result, containsString("My bean"));
|
||||
assertThat(result, not(containsString("id")));
|
||||
|
||||
+8
-4
@@ -93,7 +93,8 @@ public class JacksonBidirectionRelationUnitTest {
|
||||
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);
|
||||
final ItemWithIdentity item = new ObjectMapper().readerFor(ItemWithIdentity.class)
|
||||
.readValue(json);
|
||||
|
||||
assertEquals(2, item.id);
|
||||
assertEquals("book", item.itemName);
|
||||
@@ -104,7 +105,8 @@ public class JacksonBidirectionRelationUnitTest {
|
||||
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);
|
||||
final ItemWithSerializer item = new ObjectMapper().readerFor(ItemWithSerializer.class)
|
||||
.readValue(json);
|
||||
assertEquals(2, item.id);
|
||||
assertEquals("book", item.itemName);
|
||||
assertEquals("John", item.owner.name);
|
||||
@@ -116,7 +118,8 @@ public class JacksonBidirectionRelationUnitTest {
|
||||
final ItemWithView item = new ItemWithView(2, "book", user);
|
||||
user.addItem(item);
|
||||
|
||||
final String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(item);
|
||||
final String result = new ObjectMapper().writerWithView(Views.Public.class)
|
||||
.writeValueAsString(item);
|
||||
|
||||
assertThat(result, containsString("book"));
|
||||
assertThat(result, containsString("John"));
|
||||
@@ -129,7 +132,8 @@ public class JacksonBidirectionRelationUnitTest {
|
||||
final ItemWithView item = new ItemWithView(2, "book", user);
|
||||
user.addItem(item);
|
||||
|
||||
new ObjectMapper().writerWithView(Views.Internal.class).writeValueAsString(item);
|
||||
new ObjectMapper().writerWithView(Views.Internal.class)
|
||||
.writeValueAsString(item);
|
||||
}
|
||||
|
||||
}
|
||||
+2
-1
@@ -66,7 +66,8 @@ public class JacksonCollectionDeserializationUnitTest {
|
||||
final String jsonArray = mapper.writeValueAsString(listOfDtos);
|
||||
// [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}]
|
||||
|
||||
final CollectionType javaType = mapper.getTypeFactory().constructCollectionType(List.class, MyDto.class);
|
||||
final CollectionType javaType = mapper.getTypeFactory()
|
||||
.constructCollectionType(List.class, MyDto.class);
|
||||
final List<MyDto> asList = mapper.readValue(jsonArray, javaType);
|
||||
assertThat(asList.get(0), instanceOf(MyDto.class));
|
||||
}
|
||||
|
||||
@@ -130,7 +130,8 @@ public class JacksonDateUnitTest {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setDateFormat(df);
|
||||
|
||||
final Event event = mapper.readerFor(Event.class).readValue(json);
|
||||
final Event event = mapper.readerFor(Event.class)
|
||||
.readValue(json);
|
||||
assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
|
||||
}
|
||||
|
||||
@@ -141,7 +142,8 @@ public class JacksonDateUnitTest {
|
||||
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final EventWithSerializer event = mapper.readerFor(EventWithSerializer.class).readValue(json);
|
||||
final EventWithSerializer event = mapper.readerFor(EventWithSerializer.class)
|
||||
.readValue(json);
|
||||
assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,9 @@ public class JacksonExceptionsUnitTest {
|
||||
final String json = "{\"animal\":{\"name\":\"lacy\"}}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
mapper.reader().forType(Zoo.class).readValue(json);
|
||||
mapper.reader()
|
||||
.forType(Zoo.class)
|
||||
.readValue(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -42,7 +44,9 @@ public class JacksonExceptionsUnitTest {
|
||||
final String json = "{\"animal\":{\"name\":\"lacy\"}}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
mapper.reader().forType(ZooConfigured.class).readValue(json);
|
||||
mapper.reader()
|
||||
.forType(ZooConfigured.class)
|
||||
.readValue(json);
|
||||
}
|
||||
|
||||
// JsonMappingException: No serializer found for class
|
||||
@@ -51,7 +55,8 @@ public class JacksonExceptionsUnitTest {
|
||||
final UserWithPrivateFields user = new UserWithPrivateFields(1, "John");
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.writer().writeValueAsString(user);
|
||||
mapper.writer()
|
||||
.writeValueAsString(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -61,7 +66,8 @@ public class JacksonExceptionsUnitTest {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
|
||||
|
||||
final String result = mapper.writer().writeValueAsString(user);
|
||||
final String result = mapper.writer()
|
||||
.writeValueAsString(user);
|
||||
assertThat(result, containsString("John"));
|
||||
}
|
||||
|
||||
@@ -71,7 +77,9 @@ public class JacksonExceptionsUnitTest {
|
||||
final String json = "{\"id\":1,\"name\":\"John\"}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
mapper.reader().forType(User.class).readValue(json);
|
||||
mapper.reader()
|
||||
.forType(User.class)
|
||||
.readValue(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -79,7 +87,9 @@ public class JacksonExceptionsUnitTest {
|
||||
final String json = "{\"id\":1,\"name\":\"John\"}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
final com.baeldung.jackson.dtos.User user = mapper.reader()
|
||||
.forType(com.baeldung.jackson.dtos.User.class)
|
||||
.readValue(json);
|
||||
assertEquals("John", user.name);
|
||||
}
|
||||
|
||||
@@ -91,7 +101,9 @@ public class JacksonExceptionsUnitTest {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
|
||||
|
||||
mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
mapper.reader()
|
||||
.forType(com.baeldung.jackson.dtos.User.class)
|
||||
.readValue(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -101,7 +113,9 @@ public class JacksonExceptionsUnitTest {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
|
||||
|
||||
final UserWithRoot user = mapper.reader().forType(UserWithRoot.class).readValue(json);
|
||||
final UserWithRoot user = mapper.reader()
|
||||
.forType(UserWithRoot.class)
|
||||
.readValue(json);
|
||||
assertEquals("John", user.name);
|
||||
}
|
||||
|
||||
@@ -111,7 +125,9 @@ public class JacksonExceptionsUnitTest {
|
||||
final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
mapper.reader()
|
||||
.forType(com.baeldung.jackson.dtos.User.class)
|
||||
.readValue(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -119,8 +135,10 @@ public class JacksonExceptionsUnitTest {
|
||||
final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final List<com.baeldung.jackson.dtos.User> users = mapper.reader().forType(new TypeReference<List<com.baeldung.jackson.dtos.User>>() {
|
||||
}).readValue(json);
|
||||
final List<com.baeldung.jackson.dtos.User> users = mapper.reader()
|
||||
.forType(new TypeReference<List<com.baeldung.jackson.dtos.User>>() {
|
||||
})
|
||||
.readValue(json);
|
||||
|
||||
assertEquals(2, users.size());
|
||||
}
|
||||
@@ -131,7 +149,9 @@ public class JacksonExceptionsUnitTest {
|
||||
final String json = "{\"id\":1,\"name\":\"John\", \"checked\":true}";
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
mapper.reader()
|
||||
.forType(com.baeldung.jackson.dtos.User.class)
|
||||
.readValue(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -141,7 +161,9 @@ public class JacksonExceptionsUnitTest {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||
|
||||
final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
final com.baeldung.jackson.dtos.User user = mapper.reader()
|
||||
.forType(com.baeldung.jackson.dtos.User.class)
|
||||
.readValue(json);
|
||||
assertEquals("John", user.name);
|
||||
}
|
||||
|
||||
@@ -151,7 +173,9 @@ public class JacksonExceptionsUnitTest {
|
||||
final String json = "{'id':1,'name':'John'}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
mapper.reader()
|
||||
.forType(com.baeldung.jackson.dtos.User.class)
|
||||
.readValue(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -162,7 +186,9 @@ public class JacksonExceptionsUnitTest {
|
||||
factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
|
||||
final ObjectMapper mapper = new ObjectMapper(factory);
|
||||
|
||||
final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
final com.baeldung.jackson.dtos.User user = mapper.reader()
|
||||
.forType(com.baeldung.jackson.dtos.User.class)
|
||||
.readValue(json);
|
||||
assertEquals("John", user.name);
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,8 @@ public class JacksonJsonViewUnitTest {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
|
||||
|
||||
final String result = mapper.writerWithView(Views.Public.class).writeValueAsString(user);
|
||||
final String result = mapper.writerWithView(Views.Public.class)
|
||||
.writeValueAsString(user);
|
||||
|
||||
assertThat(result, containsString("John"));
|
||||
assertThat(result, not(containsString("1")));
|
||||
@@ -39,7 +40,8 @@ public class JacksonJsonViewUnitTest {
|
||||
final Item item = new Item(2, "book", "John");
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String result = mapper.writerWithView(Views.Public.class).writeValueAsString(item);
|
||||
final String result = mapper.writerWithView(Views.Public.class)
|
||||
.writeValueAsString(item);
|
||||
|
||||
assertThat(result, containsString("book"));
|
||||
assertThat(result, containsString("2"));
|
||||
@@ -52,7 +54,8 @@ public class JacksonJsonViewUnitTest {
|
||||
final Item item = new Item(2, "book", "John");
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String result = mapper.writerWithView(Views.Internal.class).writeValueAsString(item);
|
||||
final String result = mapper.writerWithView(Views.Internal.class)
|
||||
.writeValueAsString(item);
|
||||
|
||||
assertThat(result, containsString("book"));
|
||||
assertThat(result, containsString("2"));
|
||||
@@ -66,7 +69,9 @@ public class JacksonJsonViewUnitTest {
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final User user = mapper.readerWithView(Views.Public.class).forType(User.class).readValue(json);
|
||||
final User user = mapper.readerWithView(Views.Public.class)
|
||||
.forType(User.class)
|
||||
.readValue(json);
|
||||
assertEquals(1, user.getId());
|
||||
assertEquals("John", user.getName());
|
||||
}
|
||||
@@ -79,7 +84,8 @@ public class JacksonJsonViewUnitTest {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setSerializerFactory(serializerFactory);
|
||||
|
||||
final String result = mapper.writerWithView(Views.Public.class).writeValueAsString(user);
|
||||
final String result = mapper.writerWithView(Views.Public.class)
|
||||
.writeValueAsString(user);
|
||||
assertThat(result, containsString("JOHN"));
|
||||
assertThat(result, containsString("1"));
|
||||
}
|
||||
|
||||
+10
-5
@@ -109,7 +109,8 @@ public class JacksonSerializationIgnoreUnitTest {
|
||||
final MyDtoWithFilter dtoObject = new MyDtoWithFilter();
|
||||
dtoObject.setIntValue(12);
|
||||
|
||||
final String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject);
|
||||
final String dtoAsString = mapper.writer(filters)
|
||||
.writeValueAsString(dtoObject);
|
||||
|
||||
assertThat(dtoAsString, not(containsString("intValue")));
|
||||
assertThat(dtoAsString, containsString("booleanValue"));
|
||||
@@ -123,7 +124,8 @@ public class JacksonSerializationIgnoreUnitTest {
|
||||
@Override
|
||||
public final void serializeAsField(final Object pojo, final JsonGenerator jgen, final SerializerProvider provider, final PropertyWriter writer) throws Exception {
|
||||
if (include(writer)) {
|
||||
if (!writer.getName().equals("intValue")) {
|
||||
if (!writer.getName()
|
||||
.equals("intValue")) {
|
||||
writer.serializeAsField(pojo, jgen, provider);
|
||||
return;
|
||||
}
|
||||
@@ -153,7 +155,8 @@ public class JacksonSerializationIgnoreUnitTest {
|
||||
dtoObject.setIntValue(-1);
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject);
|
||||
final String dtoAsString = mapper.writer(filters)
|
||||
.writeValueAsString(dtoObject);
|
||||
|
||||
assertThat(dtoAsString, not(containsString("intValue")));
|
||||
assertThat(dtoAsString, containsString("booleanValue"));
|
||||
@@ -229,7 +232,8 @@ public class JacksonSerializationIgnoreUnitTest {
|
||||
@Test
|
||||
public final void givenAllowingMapObjectWithNullKey_whenWriting_thenCorrect() throws JsonProcessingException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.getSerializerProvider().setNullKeySerializer(new MyDtoNullKeySerializer());
|
||||
mapper.getSerializerProvider()
|
||||
.setNullKeySerializer(new MyDtoNullKeySerializer());
|
||||
|
||||
final MyDto dtoObject1 = new MyDto();
|
||||
dtoObject1.setStringValue("dtoObjectString1");
|
||||
@@ -251,7 +255,8 @@ public class JacksonSerializationIgnoreUnitTest {
|
||||
@Test
|
||||
public final void givenAllowingMapObjectOneNullKey_whenWritingMapObjectWithTwoNullKeys_thenOverride() throws JsonProcessingException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.getSerializerProvider().setNullKeySerializer(new MyDtoNullKeySerializer());
|
||||
mapper.getSerializerProvider()
|
||||
.setNullKeySerializer(new MyDtoNullKeySerializer());
|
||||
|
||||
final MyDto dtoObject1 = new MyDto();
|
||||
dtoObject1.setStringValue("dtoObject1String");
|
||||
|
||||
@@ -25,8 +25,10 @@ public class RestLoaderRequestDeserializer extends StdDeserializer<RestLoaderReq
|
||||
try {
|
||||
final ObjectCodec objectCodec = jp.getCodec();
|
||||
final JsonNode node = objectCodec.readTree(jp);
|
||||
final String className = node.get("className").textValue();
|
||||
final String fieldName = node.get("fieldName").textValue();
|
||||
final String className = node.get("className")
|
||||
.textValue();
|
||||
final String fieldName = node.get("fieldName")
|
||||
.textValue();
|
||||
|
||||
final Class<?> clazz = Class.forName(className);
|
||||
|
||||
|
||||
@@ -35,8 +35,7 @@ public class XMLSerializeDeserializeUnitTest {
|
||||
@Test
|
||||
public void whenJavaGotFromXmlStr_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
SimpleBean value = xmlMapper.readValue(
|
||||
"<SimpleBean><x>1</x><y>2</y></SimpleBean>", SimpleBean.class);
|
||||
SimpleBean value = xmlMapper.readValue("<SimpleBean><x>1</x><y>2</y></SimpleBean>", SimpleBean.class);
|
||||
assertTrue(value.getX() == 1 && value.getY() == 2);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user