Last active
October 25, 2020 19:09
-
-
Save diegoicosta/f06f61720f02b8c00afddb146ade5cce to your computer and use it in GitHub Desktop.
Using Jackson to create manually a JsonNode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Manually, no big deal | |
* ObjectNode representes a Json. When you create a HTTP Post, this object should be enough or send it as a converted String | |
**/ | |
public class JsonJacksonTest { | |
@Test | |
public void testJsonByHand() { | |
ObjectMapper objectMapper = new ObjectMapper(); | |
ObjectNode objectNode = objectMapper.createObjectNode(); | |
objectNode.put("attribute1", "value1"); | |
objectNode.put("attribute2", "value2"); | |
System.out.println(objectNode.toString()); | |
} | |
} | |
/** Using Custom Serializer example **/ | |
public class CountrySerializer extends StdSerializer<Country> { | |
protected CountrySerializer(Class<Country> t) { | |
super(t); | |
} | |
public CountrySerializer() { | |
this(null); | |
} | |
@Override | |
public void serialize(Country country, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { | |
jsonGenerator.writeStartObject(); | |
jsonGenerator.writeStringField("countryName", country.getDisplayName()); | |
jsonGenerator.writeEndObject(); | |
} | |
} | |
/** | |
* This also works. You can use Jackson ObjectMapper to convert a Country object to Json String configuring it to use the | |
* custom serializer. | |
**/ | |
public class JacksonCustomSerializer { | |
@Test | |
public void testCustomCountrySerializer() throws JsonProcessingException { | |
Country country = new Country(); | |
country.setDisplayName("Wakanda"); | |
ObjectMapper mapper = new ObjectMapper(); | |
SimpleModule module = new SimpleModule(); | |
module.addSerializer(Country.class, new CountrySerializer()); | |
mapper.registerModule(module); | |
String serialized = mapper.writeValueAsString(country); | |
System.out.println(serialized); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment