Created
October 16, 2013 15:10
-
-
Save TomDemeranville/7009250 to your computer and use it in GitHub Desktop.
JUnit test and Demonstration of Jackson @JsonAnyGetter annotation
This file contains hidden or 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
import java.util.Map; | |
import java.util.TreeMap; | |
import org.junit.Test; | |
import com.fasterxml.jackson.annotation.JsonAnyGetter; | |
import com.fasterxml.jackson.annotation.JsonProperty; | |
import com.fasterxml.jackson.core.JsonProcessingException; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
/* | |
outputs and assertsEquality for: | |
{"key1":{"value":"5","visibility":"a&b&!c"},"key2":{"value":"10","visibility":"a&b"}} | |
{"visibility":{"key1":"a&b&!c","key2":"a&b"},"key1":"5","key2":"10"} | |
I coulddn;t be | |
*/ | |
public class JSONAnnotationTest { | |
public class MyValue{ | |
String value; | |
String visibility; | |
public String getValue() { | |
return value; | |
} | |
public void setValue(String value) { | |
this.value = value; | |
} | |
public String getVisibility() { | |
return visibility; | |
} | |
public void setVisibility(String visibility) { | |
this.visibility = visibility; | |
} | |
public MyValue(String value, String visibility) { | |
super(); | |
this.value = value; | |
this.visibility = visibility; | |
} | |
} | |
public class Whatever{ | |
Map<String,String> keyvalues = new TreeMap<String,String>(); | |
@JsonProperty | |
Map<String,String> visibility = new TreeMap<String,String>(); | |
@JsonAnyGetter | |
public Map<String, String> getKeyvalues() { | |
return keyvalues; | |
} | |
} | |
@Test | |
public final void testAll() throws JsonProcessingException { | |
Map<String,MyValue> demoMap = new TreeMap<String,MyValue>(); | |
demoMap.put("key1",new MyValue("5","a&b&!c")); | |
demoMap.put("key2",new MyValue("10","a&b")); | |
ObjectMapper mapper = new ObjectMapper(); | |
System.out.println(mapper.writeValueAsString(demoMap)); | |
assertEquals("{\"key1\":{\"value\":\"5\",\"visibility\":\"a&b&!c\"},\"key2\":{\"value\":\"10\",\"visibility\":\"a&b\"}}",mapper.writeValueAsString(demoMap)); | |
Whatever w = new Whatever(); | |
w.keyvalues.put("key1", "5"); | |
w.keyvalues.put("key2", "10"); | |
w.visibility.put("key1", "a&b&!c"); | |
w.visibility.put("key2", "a&b"); | |
System.out.println(mapper.writeValueAsString(w)); | |
assertEquals("{\"visibility\":{\"key1\":\"a&b&!c\",\"key2\":\"a&b\"},\"key1\":\"5\",\"key2\":\"10\"}",mapper.writeValueAsString(w)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment