Created
July 26, 2017 18:18
-
-
Save whaley/5a52003ad43fd0ebf6bc3d80a5f107fc to your computer and use it in GitHub Desktop.
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
package jackson; | |
import com.fasterxml.jackson.annotation.JsonProperty; | |
import com.fasterxml.jackson.core.JsonGenerator; | |
import com.fasterxml.jackson.databind.JsonSerializer; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import com.fasterxml.jackson.databind.SerializerProvider; | |
import com.fasterxml.jackson.databind.annotation.JsonSerialize; | |
import java.io.IOException; | |
public class Test { | |
private static class Foo { | |
@JsonProperty("bar") | |
@JsonSerialize(using = BarToString.class) | |
Bar bar; | |
} | |
static class Bar { | |
String s = ""; | |
Bar(String s) { | |
this.s = s; | |
} | |
} | |
private static class BarToString extends JsonSerializer<Bar> { | |
@Override | |
public void serialize(Bar bar, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws | |
IOException { | |
jsonGenerator.writeString(bar.s); | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
ObjectMapper objectMapper = new ObjectMapper(); | |
Foo foo = new Foo(); | |
foo.bar = new Bar("yyy"); | |
String json = objectMapper.writeValueAsString(foo); | |
System.out.println(json); //{"bar":"yyy"} | |
Foo fooDeserialized = objectMapper.readValue(json, Foo.class); | |
System.out.println(fooDeserialized.bar.s); //yyy | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment