I have three different classes (e.g. X, Y, and Z) with some fields/variables. After setting values of these fields, i would like to map them to a JSON object. And then this JSON object should be converted to a String value. How to do this ?
Asked
Active
Viewed 227 times
1 Answers
0
You can use the javax.json to map a class into a json object and then use the toString to obtain the string of the json object built.
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
public String getString(CustomClass custom) {
JsonObjectBuilder customBuilder = Json.createObjectBuilder();
customBuilder.add("param1", custom.getParam1())
.add("param2", custom.getParam2());
JsonObject customJsonObject = customBuilder.build();
return customJsonObject.toString();
}

user1507487
- 1
- 1
-
`javax.json` is not part of the standard Java API. You need to caveate that in your answer. It is part of `maven`which the OP did not add a tag for. – WJS Jan 24 '20 at 16:10