Skip to content

Instantly share code, notes, and snippets.

@jeorfevre
Last active May 3, 2016 18:28
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 jeorfevre/7c94d4b36a809d4acf2f188f204a8058 to your computer and use it in GitHub Desktop.
Save jeorfevre/7c94d4b36a809d4acf2f188f204a8058 to your computer and use it in GitHub Desktop.
package com.rizze.test.labs.sof;
public class Brand {
protected int id;
protected String name;
}
package com.rizze.test.labs.sof;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Product {
protected int id;
protected String name;
@JsonProperty("brand") //not necessary ... but written
protected Brand brand;
}
package com.rizze.test.labs.sof;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rizze.test.entity.EntityJunit_Test;
/**
* http://stackoverflow.com/questions/37010891/how-to-map-a-nested-value-to-a-property-using-jackson-annotations/37011531#37011531
* @author Jean-Emmanuel
* @company RIZZE
*
*/
public class SOF_37010891 extends EntityJunit_Test{
@Test
public void test() {
Brand b = new Brand();
b.id=1;
b.name="RIZZE";
Product p = new Product();
p.brand=b;
p.id=12;
p.name="bigdata";
//mapper
ObjectMapper o = new ObjectMapper();
o.registerSubtypes(Brand.class);
o.registerSubtypes(Product.class);
o.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
String json=null;
try {
json = o.writeValueAsString(p);
assertTrue(json!=null);
logger.info(json);
Product p2;
try {
p2 = o.readValue(json, Product.class);
assertTrue(p2!=null);
assertTrue(p2.id== p.id);
assertTrue(p2.name.compareTo(p.name)==0);
assertTrue(p2.brand.id==p.brand.id);
logger.info("SUCCESS");
} catch (IOException e) {
e.printStackTrace();
fail(e.toString());
}
} catch (JsonProcessingException e) {
e.printStackTrace();
fail(e.toString());
}
}
}
@jeorfevre
Copy link
Author

Return from console :
2016-05-03 15:21:42 396 INFO {"id":12,"name":"bigdata","brand":{"id":1,"name":"RIZZE"}} / MReloadDB:40
2016-05-03 15:21:42 397 INFO SUCCESS / MReloadDB:49

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