Skip to content

Instantly share code, notes, and snippets.

@dadoonet
Created November 21, 2011 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dadoonet/1383346 to your computer and use it in GitHub Desktop.
Save dadoonet/1383346 to your computer and use it in GitHub Desktop.
MyEnum
package fr.pilato.test.jackson;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonSerialize
public class MyClass {
@JsonSerialize
private String myProp;
@JsonSerialize
private MyEnum myEnum;
public MyClass() {
}
public MyClass(String myProp, MyEnum myEnum) {
super();
this.myProp = myProp;
this.myEnum = myEnum;
}
public MyEnum getMyEnum() {
return myEnum;
}
public String getMyProp() {
return myProp;
}
public void setMyEnum(MyEnum myEnum) {
this.myEnum = myEnum;
}
public void setMyProp(String myProp) {
this.myProp = myProp;
}
}
package fr.pilato.test.jackson;
import org.codehaus.jackson.map.annotate.JsonSerialize;
public enum MyEnum {
ENUM1("My Enum 1"),
ENUM2("My Enum 2");
@JsonSerialize
private String value;
private MyEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>fr.pilato.test</groupId>
<artifactId>jackson</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
package fr.pilato.test.jackson;
import static org.junit.Assert.*;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
import org.junit.Test;
public class SerializeTest {
@Test
public void test() {
MyClass myClass = new MyClass("test1", MyEnum.ENUM1);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(Feature.AUTO_DETECT_FIELDS, false);
mapper.configure(Feature.AUTO_DETECT_GETTERS, false);
mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
try {
String result = mapper.writeValueAsString(myClass);
System.out.println(result);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@dadoonet
Copy link
Author

Output is {"myProp":"test1","myEnum":"ENUM1"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment