I have a REST controller that returns an Object. I want to set the PropertyNamingStrategy at the time of controller action response. For instance, based on who calls this controller, I wanna respond by sending a Camel case naming convention, and in another case return a Snake case naming style. I can use an object mapper in my controller action but that only returns a String type. I still want my Object type but with different naming convention. Any suggestions?
I'm using Springboot 2.x.
I figured out how to solve this problem. I extended the naming strategy like:
public class GetSnakeCaseSetCamelCaseNamingStrategy
extends PropertyNamingStrategy.PropertyNamingStrategyBase {
#Override
public String translate(String propertyName) {
return propertyName;
}
#Override
public String nameForGetterMethod(
MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
return PropertyNamingStrategy.SNAKE_CASE.nameForGetterMethod(config, method, defaultName);
}
#Override
public String nameForSetterMethod(
MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
return PropertyNamingStrategy.UPPER_CAMEL_CASE.nameForSetterMethod(config, method, defaultName);
}
}
Then annotated my Pojo with my own naming strategy and it worked!
If your rest controller returns a POJO and that POJO needs to be converted to JSON with different naming strategy eg SNAKE_CASE for a given type of user and CAMEL_CASE for other type of user based on your requirement, then you need to create your own HttpMessageConverter and register it with Spring.
Your Custom HttpMessageConverter looks like this:-
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.exc.InvalidDefinitionException;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.util.TypeUtils;
import java.io.IOException;
import java.lang.reflect.Type;
class CustomJackson2HttpMessageConverter
extends MappingJackson2HttpMessageConverter {
private static final ObjectMapper snakeCaseObjectMapper = new ObjectMapper()
.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
ObjectMapper defaultObjectMapper = new ObjectMapper();
#Override
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
MediaType contentType = outputMessage.getHeaders().getContentType();
JsonEncoding encoding = getJsonEncoding(contentType);
//Note:- Get the appropriate ObjectMapper and use them to write Object to Json string accordingly
ObjectMapper objectMapper = getObjectMapper(outputMessage);
JsonGenerator generator = objectMapper.getFactory().createGenerator(outputMessage.getBody(), encoding);
try {
writePrefix(generator, object);
Class<?> serializationView = null;
FilterProvider filters = null;
Object value = object;
JavaType javaType = null;
if (object instanceof MappingJacksonValue) {
MappingJacksonValue container = (MappingJacksonValue) object;
value = container.getValue();
serializationView = container.getSerializationView();
filters = container.getFilters();
}
if (type != null && TypeUtils.isAssignable(type, value.getClass())) {
javaType = getJavaType(type, null);
}
ObjectWriter objectWriter;
if (serializationView != null) {
objectWriter = objectMapper.writerWithView(serializationView);
} else if (filters != null) {
objectWriter = objectMapper.writer(filters);
} else {
objectWriter = objectMapper.writer();
}
if (javaType != null && javaType.isContainerType()) {
objectWriter = objectWriter.forType(javaType);
}
SerializationConfig config = objectWriter.getConfig();
if (contentType != null && contentType.isCompatibleWith(MediaType.TEXT_EVENT_STREAM) &&
config.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
objectWriter = objectWriter.with(this.ssePrettyPrinter);
}
objectWriter.writeValue(generator, value);
writeSuffix(generator, object);
generator.flush();
} catch (InvalidDefinitionException ex) {
throw new HttpMessageConversionException("Type definition error: " + ex.getType(), ex);
} catch (JsonProcessingException ex) {
throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getOriginalMessage(), ex);
}
}
ObjectMapper getObjectMapper(HttpOutputMessage outputMessage) {
HttpHeaders responseHeaders = outputMessage.getHeaders();
/** TODO:- Check in responseHeaders if it is a specific user demanding
* response with PropertyNamingStrategy as PropertyNamingStrategy.SNAKE_CASE
* For eg:- you can have a header with name- jsonNamingStrategy=SNAKE_CASE or any default value or empty
* Based on jsonNamingStrategy you can decide if user wants response in SnakeCase or default one
* Return appropriately based on your check. For now returning snakeCaseObjectMapper
**/
return snakeCaseObjectMapper;
}
}
And you need to register your CustomJackson2HttpMessageConverter with Spring as:-
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
#EnableWebMvc
#Configuration
class WebConfig implements WebMvcConfigurer {
#Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
final MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter = new CustomJackson2HttpMessageConverter();
//Replace the default MappingJackson2HttpMessageConverter with the CustomJackson2HttpMessageConverter
converters.replaceAll(it -> it instanceof MappingJackson2HttpMessageConverter ? customJackson2HttpMessageConverter : it);
if (!converters.contains(customJackson2HttpMessageConverter)) {
converters.add(customJackson2HttpMessageConverter);
}
}
}
Similarly if you want to handle the scenario where you want to parse JSON with different naming strategy to POJO, then you can override method readInternal() of the CustomJackson2HttpMessageConverter.
Related
With this data model...
TestClass.kt
data class TestClass (val bar: Optional<Double>?)
My goal is to deserialize the following json values as such:
{"foo": 3.5} --> foo = 3.5
{"foo": null} --> foo = Optional.empty() // This is currently my problem. foo is null and I can't seem to fix it
{} --> foo = null
I've seen the solution here and tried this, but the breakpoints in my "deserialize" method never seem to hit.
OptionalDeserializer.java
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import java.io.IOException;
import java.util.Optional;
public class OptionalDeserializer extends JsonDeserializer<Optional<?>> implements ContextualDeserializer {
private JavaType valueType;
#Override
public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) {
this.valueType = property.getType().containedType(0);
return this;
}
#Override
public Optional<?> deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
final JsonNode node = parser.getCodec().readTree(parser);
return node.isNull()
? Optional.empty()
: Optional.of(context.readValue(parser, valueType));
}
}
TestDeserialization.kt
fun main(): {
val objectMapper = ObjectMapper().registerModule(KotlinModule())
val module = SimpleModule()
module.addDeserializer(Optional::class.java, OptionalDeserializer())
objectMapper.registerModule(module)
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true)
objectMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true)
objectMapper.nodeFactory = JsonNodeFactory.withExactBigDecimals(true)
val inputJson = """{"foo" : null}"""
val expectedObject = TestClass(foo = Optional.empty())
val actualObject = objectMapper.readValue(inputJson, TestClassBravo::class.java)
assertEquals(expectedObject, actualObject)
}
build.gradle (for version info)
compile 'com.fasterxml.jackson.core:jackson-databind:2.9.8'
compile 'com.fasterxml.jackson.module:jackson-module-kotlin:2.9.8'
There are two ways you can handle this.
It would be easier not to use a custom serializer, but rely on the jackson default Jdk8Module (see here)
If you want your custom Deserializer, you need to specify the null access pattern, else the deserializer will not be called for null values:
Code for 2:
// In OptionalDeserializer
#Override
public AccessPattern getNullAccessPattern() {
return AccessPattern.CONSTANT;
}
I'm working on Jackson configuration and I wonder if there is any option to deserialise different kinds of field patterns.
For example, I have an object:
class DeserializeIt {
String fieldOne;
String fieldOneAndHalf;
String fieldTwo;
String fieldThree;
String fieldFour;
//getters setters etc.
}
And I have below JSON payload:
{
"fieldOne" : "value1",
"field_ONE-and_Half": "value15",
"FIELD_TWO": "value2",
"FIELD_THREE" : "value3",
"field_four": "value4"
}
I would like to deserialize all these field names to camel case without an exception.
I tried to create my custom PropertyNamingStrategy but it goes from another direction: it does not convert delimitered fields to camel case, it tries to convert the objects fields and search for them in the parsed string.
And since I cannot pass a list of possible strings instead of one variation (fieldOne can become field-one, field_one, field-ONE etc.), this does not work.
Do you know what else could I configure for such a relaxed deserialization?
We need to extend com.fasterxml.jackson.databind.deser.BeanDeserializerModifier and com.fasterxml.jackson.databind.deser.BeanDeserializer which deserialises POJO classes. Below solution depends from version you are using because I copied some code from base class which is not ready for intercepting extra functionality. If you do not have any extra configuration for your POJO classes vanillaDeserialize method will be invoked and this one we will try to improve.
In other case you need to debug this deserialiser and updated other places if needed. Below solution uses version 2.9.8.
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.BeanDeserializer;
import com.fasterxml.jackson.databind.deser.BeanDeserializerBase;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.SettableBeanProperty;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
SimpleModule relaxedModule = new SimpleModule();
relaxedModule.setDeserializerModifier(new RelaxedBeanDeserializerModifier());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(relaxedModule);
System.out.println(mapper.readValue(jsonFile, DeserializeIt.class));
}
}
class RelaxedBeanDeserializerModifier extends BeanDeserializerModifier {
#Override
public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
JsonDeserializer<?> base = super.modifyDeserializer(config, beanDesc, deserializer);
if (base instanceof BeanDeserializer) {
return new RelaxedBeanDeserializer((BeanDeserializer) base);
}
return base;
}
}
class RelaxedBeanDeserializer extends BeanDeserializer {
private Map<String, String> properties = new HashMap<>();
public RelaxedBeanDeserializer(BeanDeserializerBase src) {
super(src);
_beanProperties.forEach(property -> {
properties.put(property.getName().toLowerCase(), property.getName());
});
}
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
// common case first
if (p.isExpectedStartObjectToken()) {
if (_vanillaProcessing) {
return vanillaDeserialize(p, ctxt, p.nextToken());
}
// 23-Sep-2015, tatu: This is wrong at some many levels, but for now... it is
// what it is, including "expected behavior".
p.nextToken();
if (_objectIdReader != null) {
return deserializeWithObjectId(p, ctxt);
}
return deserializeFromObject(p, ctxt);
}
return _deserializeOther(p, ctxt, p.getCurrentToken());
}
protected Object vanillaDeserialize(JsonParser p, DeserializationContext ctxt, JsonToken t) throws IOException {
final Object bean = _valueInstantiator.createUsingDefault(ctxt);
// [databind#631]: Assign current value, to be accessible by custom serializers
p.setCurrentValue(bean);
if (p.hasTokenId(JsonTokenId.ID_FIELD_NAME)) {
String propName = p.getCurrentName();
do {
String relaxedName = getRelaxedName(propName);
String mappedName = properties.get(relaxedName);
defaultImplementation(p, ctxt, bean, mappedName);
} while ((propName = p.nextFieldName()) != null);
}
return bean;
}
private void defaultImplementation(JsonParser p, DeserializationContext ctxt, Object bean, String propName) throws IOException {
p.nextToken();
SettableBeanProperty prop = _beanProperties.find(propName);
if (prop != null) { // normal case
try {
prop.deserializeAndSet(p, ctxt, bean);
} catch (Exception e) {
wrapAndThrow(e, bean, propName, ctxt);
}
return;
}
handleUnknownVanilla(p, ctxt, bean, propName);
}
private String getRelaxedName(String name) {
return name.replaceAll("[_\\-]", "").toLowerCase();
}
}
Above code prints:
DeserializeIt{fieldOne='value1', fieldOneAndHalf='value15', fieldTwo='value2', fieldThree='value3', fieldFour='value4'}
See also:
Can Jackson check for duplicated properties in a case insensitive way?
From Jackson 2.9, you can provide multiple possible properties names for deserialization using the
#JsonAlias annotation. On your example, it would be like this:
class DeserializeIt {
#JsonAlias("fieldOne")
String fieldOne;
#JsonAlias("field_ONE-and_Half")
String fieldOneAndHalf;
#JsonAlias("FIELD_TWO")
String fieldTwo;
#JsonAlias("FIELD_THREE")
String fieldThree;
// and so on...
}
What worked for myself: I added an AOP component that renames all the fields of incoming object into the Camel case.
I'm trying to use the validation annotations within a pojo object by sending json in the body of the request and converting the json to the pojo object. What I would like to do is have the service consuming this json to return a bad request if the object is not valid. Does anyone know how to go about doing this? I've seen plenty of tutorials that show how to do form validation using the annotations, but what about just a simple json request?
POJO Object:
import play.data.validation.Constraints.*;
public class TestObject {
#Required
#Min(0)
public Integer testInt;
public Integer getTestInt() {
return testInt;
}
public void setTestInt(Integer testInt) {
this.testInt = testInt;
}
}
I could probably look at every element by parsing the json and validate it that way, but that seems ridiculous...
import models.Domain;
import play.libs.Json;
import play.mvc.BodyParser;
import play.mvc.Controller;
import play.mvc.Result;
import com.fasterxml.jackson.databind.JsonNode;
public class TestController extends Controller {
#BodyParser.Of(value = BodyParser.Json.class, maxLength = 10 * 1024)
public static Result create() {
JsonNode json = request().body().asJson();
TestObject testObject = Json.fromJson(json, TestObject.class);
//would like to validate the object here, based on annotations
//in the bean object...
//only if the object is valid, return ok...
return ok(json);
}
}
Thanks Peace!!
Since Play 2.5 Form.form(...) is deprecated.
Here is how you should do it now:
private FormFactory formFactory;
#Inject
YourContructor(FormFactory formFactory){
this.formFactory
}
#BodyParser.Of(value = BodyParser.Json.class, maxLength = 10 * 1024)
public static Result create() {
JsonNode json = request().body().asJson();
Form<TestObject > TestObjectValidationForm = formFactory.form(TestObject .class)
.bind(json);
if(TestObjectValidationForm .hasErrors())
return badRequest("Invalid");
TestObject testObject = Json.fromJson(json, TestObject.class);
//only if the object is valid, return ok...
return ok(json);
}
Anyway, I don't really like to use form to do it... there is no better option?
this is what i'll do
#BodyParser.Of(value = BodyParser.Json.class, maxLength = 10 * 1024)
public static Result create() {
JsonNode json = request().body().asJson();
//this is not neccessary for validation except maybe to be sure the json can be
//mapped back to pojo before validating then you'll have to wrap
//this statement in a try catch so you can recover from any errors during mapping
//TestObject testObject = Json.fromJson(json, TestObject.class);
Form<TestObject> testObjectForm = Form.form(TestObject.class);
Form<TestObject> testObjForm = testObjectForm.bind(json);
if(testObjForm.hasErrors){
doStuff()
}else{
return ok(json);
}
}
Using Jackson and jackson-dataformat-xml 2.4.4, I'm trying to deserialize a XML document where a collection annotated with #XmlWrapperElement may have zero elements, but where the XML contains whitespace (in my case a line break). Jackson throws a JsonMappingException on this content with the message “Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token”. I cannot change the way the XML is produced.
Example:
static class Outer {
#XmlElementWrapper
List<Inner> inners;
}
static class Inner {
#XmlValue
String foo;
}
ObjectMapper mapper = new XmlMapper().registerModules(new JaxbAnnotationModule());
String xml = "<outer><inners>\n</inners></outer>";
Outer outer = mapper.readValue(xml, Outer.class);
The following workarounds do not work:
Enabling DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY: In this case Jackson wants to instantiate a bogus instance of Inner using the whitespace as content.
Creating setters for this field for both String and the collection type. In this case I get a JsonMappingException (“Conflicting setter definitions for property "inners"”).
In a similar Stackoverflow question it is suggested to downgrade Jackson to 2.2.3. This does not fix the problem for me.
Any suggestions?
Edit: I can work around this issue by wrapping the CollectionDeserializer and checking for a whitespace token. This looks however very fragile to me, e.g. I had to override another method to rewrap the object. I can post the workaround, but a cleaner approach would be better.
A workaround for this problem is to wrap the standard CollectionDeserializer to return an empty collection for tokens containing whitespace and register the new Deserializer. I put the code into a Module so it can be registered easily:
import java.io.IOException;
import java.util.Collection;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.std.CollectionDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.type.CollectionType;
public class XmlWhitespaceModule extends SimpleModule {
private static class CustomizedCollectionDeserialiser extends CollectionDeserializer {
public CustomizedCollectionDeserialiser(CollectionDeserializer src) {
super(src);
}
private static final long serialVersionUID = 1L;
#SuppressWarnings("unchecked")
#Override
public Collection<Object> deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
if (jp.getCurrentToken() == JsonToken.VALUE_STRING
&& jp.getText().matches("^[\\r\\n\\t ]+$")) {
return (Collection<Object>) _valueInstantiator.createUsingDefault(ctxt);
}
return super.deserialize(jp, ctxt);
}
#Override
public CollectionDeserializer createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException {
return new CustomizedCollectionDeserialiser(super.createContextual(ctxt, property));
}
}
private static final long serialVersionUID = 1L;
#Override
public void setupModule(SetupContext context) {
super.setupModule(context);
context.addBeanDeserializerModifier(new BeanDeserializerModifier() {
#Override
public JsonDeserializer<?> modifyCollectionDeserializer(
DeserializationConfig config, CollectionType type,
BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
if (deserializer instanceof CollectionDeserializer) {
return new CustomizedCollectionDeserialiser(
(CollectionDeserializer) deserializer);
} else {
return super.modifyCollectionDeserializer(config, type, beanDesc,
deserializer);
}
}
});
}
}
After that you can add it to your ObjectMapper like this:
ObjectMapper mapper = new XmlMapper().registerModule(new XmlWhitespaceModule());
I am implementing restful API where i would like the caller to specify the specific properties that one likes to be serialized something like /dogs/1?fields=name,breed. So if the dog has many more properties other than name and breed and I am using a standard serialization library like jackson how can i tell jackson to ignore the rest of the properties while serializing in runtime?
In other words what is the way to tell jackson to dynamically ignore some properties at runtime?
You did not specify version of Jackson library, so I assume that you are using 2.2.0 or newest. In Jackson this is not easy task to do but we can do it, for example, with BasicClassIntrospector. Below source code shows how it should look like. For example we have one POJO class:
class User {
private String name;
private String surname;
// getters/setters
}
We have to define new BasicClassIntrospector which returns bean definition object only with this fields which we need:
class ExclusionAnnotationIntrospector extends BasicClassIntrospector {
private Collection<String> properties;
public ExclusionAnnotationIntrospector(Collection<String> properties) {
this.properties = properties;
}
#Override
public BasicBeanDescription forSerialization(SerializationConfig serializationConfig,
JavaType javaType, MixInResolver mixInResolver) {
BasicBeanDescription beanDesc = super.forSerialization(serializationConfig, javaType,
mixInResolver);
deleteUnwantedProperties(beanDesc);
return beanDesc;
}
private void deleteUnwantedProperties(BasicBeanDescription beanDesc) {
List<BeanPropertyDefinition> beanProperties = new ArrayList<BeanPropertyDefinition>(
beanDesc.findProperties());
for (BeanPropertyDefinition bpd : beanProperties) {
String name = bpd.getName();
if (!properties.contains(name)) {
beanDesc.removeProperty(name);
}
}
}
}
Now, we have to create new ObjectMapper class with above introspector. We have to define properties we need in constructor:
class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper(Collection<String> properties) {
this._serializationConfig = getSerializationConfig().with(
new ExclusionAnnotationIntrospector(properties));
}
}
And, finally, example usage:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.introspect.BasicBeanDescription;
import com.fasterxml.jackson.databind.introspect.BasicClassIntrospector;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
public class JacksonProgram {
public static void main(String[] args) throws Exception {
User user = new User();
user.setName("Tom");
user.setSurname("Garnier");
CustomObjectMapper onlyNameSerializer = new CustomObjectMapper(toSet("name"));
CustomObjectMapper onlySurnameSerializer = new CustomObjectMapper(toSet("surname"));
CustomObjectMapper fullUserSerializer = new CustomObjectMapper(toSet("name", "surname"));
System.out.println(onlyNameSerializer.writeValueAsString(user));
System.out.println(onlySurnameSerializer.writeValueAsString(user));
System.out.println(fullUserSerializer.writeValueAsString(user));
}
private static Set<String> toSet(String... params) {
HashSet<String> set = new HashSet<String>();
for (String item : params) {
set.add(item);
}
return set;
}
}
Above program prints:
{"name":"Tom"}
{"surname":"Garnier"}
{"name":"Tom","surname":"Garnier"}
I'd recommend to take a look at http://flexjson.sourceforge.net/
(in particular section Working With Includes/Excludes)
Example:
public String toJsonWithIncludes(Object obj, String...includes) {
return new JSONSerializer()
.include(includes)
.exclude("data.*","*.class")
.serialize(obj);
}
...
toJsonWithIncludes(obj, "name","breed");