Java object to JSON with only selected fields
You can use Jackson to solve your problem. Follow the given below step -
Step 1 . Create a method that converts Java object to Json
public class JsonUtils {
public static String javaToJson(Object o) {
String jsonString = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.UNWRAP_ROOT_VALUE,true);
jsonString = objectMapper.writeValueAsString(o);
} catch (JsonGenerationException e) {
logger.error(e);
} catch (JsonMappingException e) {
logger.error(e);
} catch (IOException e) {
logger.error(e);
}
return jsonString;
}
}
Step 2 Model class
package com.javamad.model;
import org.codehaus.jackson.annotate.JsonIgnore;
public class Sample{
int foo=5;
public int getFoo() {
return foo;
}
public void setFoo(int foo) {
this.foo = foo;
}
@JsonIgnore
public int getBar() {
return bar;
}
public void setBar(int bar) {
this.bar = bar;
}
int bar=6;
}
Step 3 Convert your java class to json
Sample sample = new Sample()
JsonUtils.javaToJson(sample);
source to share
Do I have to compose the JSON string manually
Avoid this, it's all easy to invalidate the json this way. Using the library ensures correct escaping of characters that would otherwise break the output.
Gson ignores fields transient
:
public class Sample {
private int foo = 5;
private int transient bar = 6;
}
Gson gson = new Gson();
Or you can choose what to include with the attribute Expose
:
public class Sample {
@Expose private int foo = 5;
private int bar = 6;
}
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Then, whichever approach you take, do this:
String json = gson.toJson(obj);
To get what you want {"foo":5}
source to share
you can try Gson, JSON library to convert object to / from json.
these two methods are helpful:
toJson () - Convert a Java object to JSON format
fromJson () - Convert JSON to Java object
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
source to share