Skip to content

Instantly share code, notes, and snippets.

@juristr
Last active August 29, 2015 14:10
Show Gist options
  • Save juristr/fee92f837c4c5d32847a to your computer and use it in GitHub Desktop.
Save juristr/fee92f837c4c5d32847a to your computer and use it in GitHub Desktop.
Render some JSON

Disclaimer: I'm not a Java expert, so please provide me some enhanced version if mine is suboptimal!

What I want to achieve is to render the following "static" JSON:

{
  "errors": [
    { "name": "Server said this field is required" },
    { "name": "Oh...and this one failed as well" }
  ]
}

With Java and JAX-RS:

@GET
public Response update() {
	JsonObject jo = Json
			.createObjectBuilder()
			.add("errors",
					Json.createArrayBuilder()
						.add(Json.createObjectBuilder().add("name", "Server said this field is required"))
						.add(Json.createObjectBuilder().add("name", "oh...and something else failed as well")))
			.build();
			
	return Response.status(422).entity(jo).build();
}

In .Net with ASP.net WebApi and C#:

[HttpGet]
[Route]
public object GetSomeJson()
{
  return new {
    errors = new [] {
      new { name = "Server said this field is required" },
      new { name = "Oh...and this one failed as well" }
    }
  };
}

In Node.js ... don't add it here as it would be a copy & paste of the JSON above.. ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment