Should I compose JSON string manually
Avoid this, it's all to easy to make invalid json this way. Use of a library ensures proper escaping of characters that would otherwise break the output.
Gson ignores transient
fields:
public class Sample {
private int foo = 5;
private int transient bar = 6;
}
Gson gson = new Gson();
Or you can choose which to include with Expose
attribute:
public class Sample {
@Expose private int foo = 5;
private int bar = 6;
}
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Then whichever approach, do this:
String json = gson.toJson(obj);
To get your desired {"foo":5}