return ModelAndView when JSON is returned - json

Can we return JSON object from spring controller and write that JSON object on jsp page.
Below is my jsp page:
<script type="text/javascript">
dojo.require("dojox.grid.EnhancedGrid");
dojo.require("dojox.data.QueryReadStore");
dojo.ready(function(){
mystore=new dojo.data.ItemFileReadStore({url:"<%=request.getContextPath()%>/showData.htm"});
var layout= [
{field: 'ID', name: 'SID',formatter: hrefFormatter,datatype:"number" },
{field: 'SPREAD',name: 'SPREAD',autoComplete: true}
]
var grid = new dojox.grid.EnhancedGrid({
id: 'myGrid',
----
});
</script>
Controller:
#RequestMapping(value = "/showData", method = RequestMethod.GET)
public void getSTIDData(HttpServletRequest request,
HttpServletResponse response, #ModelAttribute VINDTO vinData,
BindingResult beException) throws IOException {
try {
......
......
XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});
xstream.alias("items", com.loans.auto.DTO.VINRequestDTO.class);
String str = xstream.toXML(vinListCopy);
StringBuffer rowData = new StringBuffer();
rowData.append("{'numRows':").append(vinListCopy.size())
.append(",'items':").append(str).append("}");
PrintWriter out = response.getWriter();
out.print(rowData);
}
Instead of getSTIDData(..) returning void , i want this method to return ModelAndView object, but when i return ModelAndView object, in jsp page data is not getting loaded and it says "NO Data Found". Please suggest. Thanks.
Below is the exception generated when i used Gson
SyntaxError {stack: "SyntaxError: Unexpected identifier↵ at Object.d… at signalWaiting (/MYWebProject/dojo/Deferred.js:28:4)", message: "Unexpected identifier"}
message: "Unexpected identifier"
stack: "SyntaxError: Unexpected identifier↵ at Object.dojo.fromJson (/MYWebProject/dojo/_base/json.js:26:23)↵ at Object.dojo._contentHandlers.dojo.contentHandlers.json (/MYWebProject/dojo/_base/xhr.js:78:16)↵ at Object.dojo._contentHandlers.dojo.contentHandlers.json-comment-optional (/MYWebProject/dojo/_base/xhr.js:156:28)↵ at _deferredOk (/MYWebProject/dojo/_base/xhr.js:432:42)↵ at notify (/MYWebProject/dojo/_base/Deferred.js:187:23)↵ at complete (/MYWebProject/dojo/_base/Deferred.js:168:4)↵ at resolve.callback (/MYWebProject/dojo/_base/Deferred.js:248:4)↵ at eval (/MYWebProject/dojo/_base/xhr.js:627:8)↵ at signalListener (/MYWebProject/dojo/Deferred.js:37:21)↵ at signalWaiting (/MYWebProject/dojo/Deferred.js:28:4)"
__proto__: Error

yes you can return as JSON response.showing with the help of Gson API
#RequestMapping(value = "/showData", method = RequestMethod.GET)
public #ResponseBody String getUserHomePage(HttpServletRequest request,HttpServletResponse response, #ModelAttribute VINDTO vinData,BindingResult beException) throws IOException {
//you code stuff to create model object bean
Gson gson = new Gson();
return gson.toJson(objectBean);
}

Keep it clean and simple...
Here is a real life snippet of code ...
#RequestMapping(value = "/actions/getImplGroups", method = RequestMethod.POST)
public ResponseEntity<String> getImplGroups(HttpServletRequest request, HttpServletResponse response) {
List<String> groups = bpmClient.getAllGroups();
ObjectMapper mapper = new ObjectMapper();
String jsonString;
try {
jsonString = mapper.writeValueAsString(groups);
} catch (JsonGenerationException e) {
jsonString = "Error with json generation: " + e.getMessage();
} catch (JsonMappingException e) {
jsonString = "Error with json mapping: " + e.getMessage();
} catch (IOException e) {
jsonString = "Error with json: " + e.getMessage();
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(jsonString, responseHeaders, HttpStatus.CREATED);
}
The important point to consider is sending the correct web header, so that your page expects to see json.
I the case above we used the Jackson library to create the json, but in truth you could format the json any way you like. Here is an example of a simple, manually formatted string...
#RequestMapping(value = "/actions/getTicketsNotUpdatedWithinShift", method = RequestMethod.POST)
public ResponseEntity<String> getTicketsNotUpdatedWithinShift(String center, String sections, String minutesInShift, Model model) {
String[] sectionArray = sections.split(",");
String json = "";
String rowsString = "";
for (String section : sectionArray) {
List<Map<String, String>> rows = service.getMinutesSinceLastTicketUpdate(center, section);
for (Map<String, String> row : rows) {
int minutesSinceUpdate = Integer.parseInt(row.get("minutes"));
if (minutesSinceUpdate > Integer.parseInt(minutesInShift)) {
String description = row.get("description");
rowsString = rowsString + "\"" + description + "\",";
}
}
}
// Build the json structure
if (!rowsString.isEmpty()) {
// Trim the trailing comma.
rowsString = rowsString.replaceAll(",$", "");
json = "[" + rowsString + "]";
} else {
json = "[]";
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}

Related

How to send the same request multiple times in the same time with java using RestTemplate,json

I need to send the same request multiple times for example post request 100 times in the same time.
My code look like this
#SpringBootTest
public class FetchApi {
String getUrl = "www.https://example/get";
String postUrl = "www.https://example/post";
String token = "adadfsdfgsdgdfgdfghdhdhdhdhdhdh";
#Test
public void getRequest() {
try {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
HttpEntity<String> entity = new HttpEntity<>("", headers);
Object res = restTemplate.exchange(getUrl, HttpMethod.GET, entity, Object.class);
System.out.println(res);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#Test
public void postRequest() {
try {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
headers.setContentType(MediaType.APPLICATION_JSON);
Workflow workflow = new Workflow("adadadasdadadad", "1adadadadadadada0","adafsadfsfsdgfdsfgdfgdg");
String json = new ObjectMapper().writeValueAsString(workflow);
HttpEntity<String> entity = new HttpEntity<>(json, headers);
Object res = restTemplate.exchange(postUrl, HttpMethod.POST, entity, Object.class);
System.out.println(res);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
This code works fine if i have value from my class workflow but how to change to value from class to json file.
My json file look that
{
"workflow":{
"guid":"adadadadadadadad"
},
"formType":{
"guid":"adadadadadadadad"
},
"formType":[
{
"guid":"adadadadadadadad",
"svalue":"adadadadadada"
},
"guid":"adadadadadadadad",
"svalue":"adadadadadada"
},
"guid":"adadadadadadadad",
"svalue":"adadadadadada"
}
]
}
Can someone give me information how to send a request multiple times at the same time with json ?
You should look at ExecutorService
#Test
public void postRequest() {
ExecutorService executors = Executors.newFixedThreadPool(100);
try {
List<Callable<Object>> tasks = new ArrayList<>();
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
headers.setContentType(MediaType.APPLICATION_JSON);
Workflow workflow = new Workflow("adadadasdadadad", "1adadadadadadada0", "adafsadfsfsdgfdsfgdfgdg");
String json = new ObjectMapper().writeValueAsString(workflow);
HttpEntity<String> entity = new HttpEntity<>(json, headers);
for (int i = 0; i < 100; i++) {
tasks.add(() ->
restTemplate.exchange(getUrl, HttpMethod.GET, entity, Object.class));
}
List<Future<Object>> futures = executors.invokeAll(tasks);
executors.awaitTermination(1, TimeUnit.MINUTES);
futures.forEach(objectFuture -> {
if(objectFuture.isDone()){
try {
System.out.println(objectFuture.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
executors.shutdown();
}
}

jsonobject for nested api's put operation

i am trying to put request by using jsonobject but i couldnt find a way to send it
how can i create put body for api like
{
"roleRight": {
"systemSetting": 0,
"userManagement": 0
}
}
right now, i created like;
public static JSONObject nspRightSet(String ssvalue, String umvalue) {
JSONObject requestParams = new JSONObject();
requestParams.put("roleRight.systemSetting", ssvalue);
requestParams.put("roleRight.userManagement", umvalue);
return requestParams;
}
and use it by;
res = given()
.header("Authorization", "Bearer " + localLogin.accessToken)
.header("Content-type", "application/json")
.contentType(ContentType.JSON)
.body(nspRightSetBody)
.when()
.put("https://localhost:8090/api/v1/roles/" + rolenameId + "/right")
.then()
.log().all()
.statusCode(201)
.extract()
.response().getBody();
}
but it gives error like;
"error": "JSON parse error: Cannot deserialize instance of `...` out of START_ARRAY token;
public static JSONObject nspRightSet(String ssvalue, String umvalue) {
JSONObject requestParams = new JSONObject();
JSONObject childJSON = new JSONObject();
childJSON.put("systemSetting", ssvalue);
childJSON.put("userManagement", umvalue);
requestParams.put("roleRight", childJSON);
return requestParams;
}

How to add attachment using TestRail API?

public static void fnUpdateResultToTestRail(String trusername, String trpassword, String trRunId,String testCaseName,String status, String testStepDetails)
throws MalformedURLException, IOException, APIException {
APIClient client = new APIClient("testrailurl");
client.setUser("username");
client.setPassword("password");
HashMap data = new HashMap();
data.put("status_id", status);
data.put("comment", testStepDetails);
HashMap data1 = new HashMap();
data1.put("attachment","C:\\Pictures\\\\X-SecurityToken-Issue.jpg";
JSONArray array = (JSONArray) client.sendGet("get_tests/"+trRunId);
//System.out.println(array.size());
for (int i = 0; i < array.size(); i++) {
JSONObject c = (JSONObject) (array.get(i));
String testrailTestCaseName=c.get("title").toString();
if (testrailTestCaseName.equals(testCaseName)) {
System.out.println(c.get("id"));
client.sendPost("add_result/" + c.get("id"), data);
client.sendPost("add_attachment_to_case/"+c.get("case_id"), data1);
break;
}
}
}
TestRail API returned HTTP 400("No file attached or upload size was exceeded.")
As per document, we need to pass Headers: { "Content-Type","value":"multipart/form-data" }
API client has inbuilt methods....
public Object sendPost(String uri, Object data)
throws MalformedURLException, IOException, APIException
{
return this.sendRequest("POST", uri, data);
}
private Object sendRequest(String method, String uri, Object data)
throws MalformedURLException, IOException, APIException
{
URL url = new URL(this.m_url + uri);
...........
}
How to add the header in this inbuilt method on run time..?
Can any one help on this?

How can I get the json file from ResponseEntity?

I have my web service consuming another web service. in my web service I modify some fields of the json. then in postman it is consumed ok.
Now I need to convert the ResponseEntity to a .json file to save it to a folder on my computer, but the attempt has failed.
Any ideas?
my controller current:
#Controller
public class SiviccController {
private final Logger log = LoggerFactory.getLogger(SiviccController.class);
private String url = "http://localhost:9090/url_1";
#GetMapping("/url_2")
#ResponseBody
public Body sivicc() {
RestTemplate restTemplate = new RestTemplate(Factory.timeoutHttp());
try {
return restTemplate.getForObject(url, Body.class);
} catch (Exception e) {
Body body = new Body();
body.setIserror(true);
log.info(e.getMessage());
return body;
}
}
}
Matheus Cirillo works perfectly with the following code:
#Controller
public class SiviccController {
private final Logger log = LoggerFactory.getLogger(SiviccController.class);
private String url = "http://localhost:9090/url_1";
#GetMapping("/url_2")
#ResponseBody
public Body sivicc() {
RestTemplate restTemplate = new RestTemplate(Factory.timeoutHttp());
try {
String response = restTemplate.getForObject(url, String.class);
BufferedWriter writer = new BufferedWriter(new FileWriter("my-file.json", true));
writer.append(response);
writer.close();
return restTemplate.getForObject(url, Body.class);
} catch (Exception e) {
Body body = new Body();
body.setIserror(true);
log.info(e.getMessage());
return body;
}
}
}
However, the web service that you were consuming before now generates a token. That's why I change getForObject to exchange and I consume it well, but I apply the same logic to save the json in a folder on my computer, but it generates a failure in two lines:
#Controller
public class SiviccController {
private final Logger log = LoggerFactory.getLogger(SiviccController.class);
private String url = "http://localhost:9090/url_1";
#GetMapping("/url_2")
#ResponseBody
public Body sivicc() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("Authorization", "bearer 8P7oM_ZDhB3TYolVkB1MLtM734DrrUSMVEFuiy3u");
HttpEntity request = new HttpEntity(headers);
headers.add("User-Agent", "Spring's RestTemplate" );
ResponseEntity<String> response = restTemplate.exchange(
url,
HttpMethod.GET,
request,
//Body.class,
String.class,
1
);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("my-file.json", true));
writer.append(response);//Error: The method append(CharSequence) in the type Writer is not applicable for the arguments (ResponseEntity<String>)
writer.close();
return response.getBody();//Error: Type mismatch: cannot convert from String to Body
} catch (Exception e) {
Body body = new Body();
body.setIserror(true);
log.info(e.getMessage());
return body;
}
}
}
Change the Response type from getForObject to String.class, then, use the BufferedWriter to write the file.
RestTemplate rest = new RestTemplate();
String response = rest.getForObject("http://example.com/", String.class);
BufferedWriter writer = new BufferedWriter(new FileWriter("my-file.json", true));
writer.append(response);
writer.close();
Edit
The RestTemplate#exchange returns a ResponseEntity<T>, not a String.
In your case, it will return a ResponseEntity<String>.
That's why you're unable to write the object. To do so, you need to get the body from the ResponseEntity object. Use the method ResponseEntity#getBody
Something like this:
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class, 1);
BufferedWriter writer = new BufferedWriter(new FileWriter("my-file.json", true));
// here you are getting the String with the response.getBody() method,
// so buffered writer can write the file
writer.append(response.getBody());
writer.close();
Resolved:
add to pom.xml:
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
</dependencies>
Use the Jackson API ObjectMapper class to convert Java Object to a JSON string
Use the BufferedWriter to write the file. #Matheus Cirillo
ObjectMapper mapper = new ObjectMapper();
try {
json = mapper.writeValueAsString(response.getBody());
System.out.println("ResultingJSONstring = " + json);
BufferedWriter writer = new BufferedWriter(new FileWriter("my-file.json", true));
writer.append(json);
writer.close();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
thanks for your help =)

How to configure Gson to serialize a set of JSR-303 ConstraintViolation objects?

I can't seem to find out how to serialize Hibernate's implementation of constraint violations using Gson.
Here's what I've tried so far.
Approach 1
MyPojo aPojo = new MyPojo();
Gson gson = new Gson();
Set<ConstraintViolation<MyPojo>> violations = validator.validate(aPojo);
System.out.println(gson.toJson(violations));
Fails with this error:
java.lang.UnsupportedOperationException:
Attempted to serialize java.lang.Class: com.bar.baz.MyPojo.
Forgot to register a type adapter?
at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:67)
at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:61)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.internal.bind.ObjectTypeAdapter.write(ObjectTypeAdapter.java:107)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:60)
at com.google.gson.Gson.toJson(Gson.java:593)
at com.google.gson.Gson.toJson(Gson.java:572)
at com.google.gson.Gson.toJson(Gson.java:527)
at com.google.gson.Gson.toJson(Gson.java:507)
Approach 2
Gson gson = new Gson();
Set<ConstraintViolation<MyPojo>> violations = validator.validate(MyPojo);
System.out.println(
gson.toJson(violations,
new TypeToken<ConstraintViolation<MyPojo>>() {}.getType())
);
Fails by not serializing MyPojo's properties:
Output: {}.
Approach 3
I was expecting this approach to delegate serialization to my custom Serializer but it still fails:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(
new TypeToken<ConstraintViolation<MyPojo>>() {}.getType(),
new JsonSerializer<ConstraintViolation<MyPojo>>() {
#Override
public JsonElement serialize(ConstraintViolation<MyPojo> src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = new JsonObject();
result.addProperty("aTestProperty", "A Test Value");
return result;
}
});
Gson gson = builder.create();
Set<ConstraintViolation<MyPojo>> violations = validator.validate(MyPojo);
System.out.println(gson.toJson(violations));
However it fails with this error:
java.lang.UnsupportedOperationException:
Attempted to serialize java.lang.Class:
com.bar.baz.MyPojo.
Forgot to register a type adapter?
at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:67)
at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:61)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.internal.bind.ObjectTypeAdapter.write(ObjectTypeAdapter.java:107)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:60)
at com.google.gson.Gson.toJson(Gson.java:593)
at com.google.gson.Gson.toJson(Gson.java:572)
at com.google.gson.Gson.toJson(Gson.java:527)
at com.google.gson.Gson.toJson(Gson.java:507)
Approach 4
Looking at the error message, I though this might work:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(
new TypeToken<ConstraintViolation<MyPojo>>() {}.getType(),
new JsonSerializer<ConstraintViolation<MyPojo>>() {
#Override
public JsonElement serialize(ConstraintViolation<MyPojo> src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = new JsonObject();
result.addProperty("aTestProperty", "A Test Value");
return result;
}
});
builder.registerTypeAdapter(
new TypeToken<MyPojo>() {}.getType(),
new JsonSerializer<MyPojo>() {
#Override
public JsonElement serialize(MyPojo src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = new JsonObject();
result.addProperty("anotherTestProperty", "Another Test Value");
return result;
}
});
Gson gson = builder.create();
Set<ConstraintViolation<MyPojo>> violations = validator.validate(MyPojo);
System.out.println(gson.toJson(violations));
But it fails with a similar error.
Approach 5: Working but ugly
The only thing that I've managed to make work is to register the serializer with the type of the vendor (Hibernate) specific implementation for ConstraintViolation:
Set<ConstraintViolation<MyPojo>> violations = validator.validate(MyPojo);
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(
new TypeToken<ConstraintViolationImpl>() {}.getType(),
new JsonSerializer<ConstraintViolation<MyPojo>>() {
#Override
public JsonElement serialize(ConstraintViolation<MyPojo> src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = new JsonObject();
result.addProperty("aTestProperty", "A Test Value");
return result;
}
});
Gson gson = builder.create();
System.out.println(gson.toJson(violations));
Is there a way to make this work without relying on the concrete implementation of ConstraintViolation (i.e. org.hibernate.validator.internal.engine.ConstraintViolationImpl)?
There doesn't seem to be a reasonable approach to serialize javax.validation.ConstraintViolation objects. In fact, even Jackson errs while trying to serialize the set:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: fromIndex(0) > toIndex(-1) (through reference chain: java.util.HashSet[0]->org.hibernate.validator.internal.engine.ConstraintViolationImpl["propertyPath"]->org.hibernate.validator.internal.engine.path.PathImpl["pathWithoutLeafNode"]->org.hibernate.validator.internal.engine.path.PathImpl["pathWithoutLeafNode"]->org.hibernate.validator.internal.engine.path.PathImpl["pathWithoutLeafNode"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
For the time being, I just convert the set of errors into a set of custom POJOs I've written and serialize that instead.
Custom ValidationError POJO:
public class ValidationError {
private String className;
private String propertyPath;
private String errorMessage;
public static Set<ValidationError> fromViolations(Set violations) {
Set<ValidationError> errors = new HashSet<ValidationError>();
for (Object o : violations) {
ConstraintViolation v = (ConstraintViolation) o;
ValidationError error = new ValidationError();
error.setClassName(v.getRootBeanClass().getSimpleName());
error.setErrorMessage(v.getMessage());
error.setPropertyPath(v.getPropertyPath().toString());
errors.add(error);
}
return errors;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getPropertyPath() {
return propertyPath;
}
public void setPropertyPath(String propertyPath) {
this.propertyPath = propertyPath;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
#Override
public String toString() {
return "ValidationError{" +
"className='" + className + '\'' +
", propertyPath='" + propertyPath + '\'' +
", errorMessage='" + errorMessage + '\'' +
'}';
}
}
Sample usage:
Set<ConstraintViolation<MyBean>> violations = validator.validate(myBean);
Set<ValidationError> errors = ValidationError.fromViolations(violations);
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(errors));
Update
For the sake of record, it is worth mentioning that XStream can serialize the set of constraint violations like a charm:
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);
System.out.println(xstream.toXML(violations));
However the generated the object graph is way too much verbose and is not suitable for use in production anyway. You can see the sample output here.