How to output json in spring mvc - json

I am using Spring boot with mvc. I have a json schema for request and response. Basically the user posts data (in json) to a url, the controller does its logic and returns a json. I am having difficulty in returning the json. So far, I have a couple of views (in thymeleaf) with hardcoded responses which I dont want. I just want to use an object which I can edit and send back to the client. The response is very simple. This is the schema of the response:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"message":{
"minLength":1,
"type":"string"
}
},
"required": [
"message"
]
}
I have an object of type response which conforms to my response json schema. I basically want to output this object to the client. But not sure how as my controller returns a String and this string is usually the name of the html page.

Add the #ResponseBody annotation to your controller method and it will use the returned value as a response rather than as a path to a page.
If you want that all methods of your controller return direct data (and not page paths), you can annotate your controller with #RestController rather than #Controller.

Related

Problem generating Spec for JSON Response type of Array of Users

I've got a Go project, exposing REST CRUD APIs, for a Mongo collection. I'm using go-swagger to generate the swagger spec. However, I'm having trouble getting the JSON response to look like I want without breaking the go-swagger spec generator.
I'm trying to use go-swagger to generate a swagger-spec from annotations on go code. I'd like to see if I can make the response just be a JSON Array of Users, like below.
Is there a way to adjust the json annotation on the User struct to produce the desired result?
[
{"id": "5d8e9aaca00ef6123c989f69", "user_name": "zbeeblebrox"},
{"id": "5d8e9ab1a00ef6123c989f6a", "user_name": "another_user"}
]
Below is what I'm getting, understandably, a JSON object, containing key "data", with a value of an Array of User objects.
I've tried redefining the swagger response struct to be an alias of type []*User, which creates the right response body, but it breaks the go swagger generator.
{
"data": [
{"id": "5d8e9aaca00ef6123c989f69", "user_name": "zbeeblebrox"},
{"id": "5d8e9ab1a00ef6123c989f6a", "user_name": "another_user"}
]
}
Here's some code.
// swagger:model
type User struct {
Id *primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"`
UserName string `json:"user_name" bson:"user_name"`
}
// HTTP status code 200 and an array of repository models in data
//swagger:response usersResp
type swaggUsersResp struct {
// in:body
Data []*User `json:"data"`
}
I also tried doing it as an alias, which provides the desired JSON response, but breaks Go-Swagger code generation. I suspect this is because the swagger:response annotation is expected to be on a struct, not an alias.
// swagger:response usersResp
type swaggUsersResp = []*User

How to define schema arbitrary JSON object?

I am trying to define a API using OAS v2 that will return a payload along with some metadata.
In other words, the response to the API will be:
{
"metadata":[
{
"key" :"key1",
"value": "value1"
}
],
"payload": {Valid JSON}
}
The payload can be anything, and different for different scenarios, the only constraint being it will be a valid JSON format. So, at this point in time, I would like to define it just as a JSON object without defining the field level details.
How can I do that in OAS2/JSON schema?
Thanks in advance.
In this case you can use an empty schema ({}) for payload.
JSON Schema relies on valid JSON value and you won't be able to supply it if your response is a malformed JSON.
If payload value is malformed, whole response will not be a valid JSON.
In other words, this issue is out of JSON Schema scope, but rather in scope of your response decoder (that should fail on malformed response body).

What is the best practice of testing JSON data?

I'm developing a server-side RESTful application which serves json data for its client applications. And I have to test so many various json outputs.
Each json has many properties and their validation methods are different like below a sample json.
So such my use-case, do you know good libraries or web services to test json data flexibly?
{
"system": { // data structure validation
"time": 1234566, // data type validation
"version": "0.0.1" // string matching validation
},
"app": { // data structure validation
"id": "1234", // string matching validation
"command": "do something", // string matching validation
"data": { // data structure validation
"hoge": "xxx", // data type validation
"fuga": 123 // data type validation
}
}
}
What do you mean by validating? validating the JSON structure or the data inside your JSON object?
To validate the structure you can parse it to another datatype like dictionary and see if you get any error while.
But to validate the data inside the object you need to validate each object in a very specific way for that object.
Use this link Just Place your JSON code and Test it. Quite easy.

How to express "arbitrary JSON" in swagger-spec?

Let's say I have a REST service that can accept any arbitrary JSON in the request body. How do I model this using swagger-spec?
I thought about Model Objects, but I could only think to wrap the arbitrary JSON (as a string) within a container JSON object, like {"payload": "{ some JSON object serialized to a string }"}, which isn't really useful.
Or, is there some other way to express that an endpoint can receive arbitrary JSON in the request body?
Model the request's body payload as parameters with schema of just "type": "object". The swagger UI editor will then prompt the user with a large textarea containing {} which they can populate with a JSON object.
"/endpoint": {
"post": {
"parameters": [
{
"description": "Arbitrary JSON object payload",
"in": "body",
"name": "body",
"required": true,
"schema": {
"type": "object"
}
}
]
}
Swagger tries to be deterministic when it comes to APIs, so what you're asking is not directly supported.
The only way I can think of to achieve what you want is to set the "consumes" property to "application/json" and add a "body" parameter of type string. This would in theory say that only JSON should be sent, but in effect, any string could be sent.
Also, this may break some third party tools if they'd try to convert to string to a JSON object before sending it to the server.

Ember insert underscore in json-serialization

i have the following JSON-GET response:
{
"check_lists": [
{
"id": 2,
"name": "Servicebesuch",
"description": ""
}]
}
Problem is the "check_lists" name which i have solved in one of the extract/extractSingle methods of the RESTSerializer so the data is loaded and deserialized successfully to the model named App.Checklist.
Now i got stucked again.
For serialization of my model-data to json, i have to do the same trick reverse but i can not find a hook for that. The serialize Method of the RESTSerializer gets only the pure record and the serialized json, received from this._super... call, does only hold the serialized object and not the call itself.
The server expects a PUT request (in case of updating a list) with the parameter packed in a param named check_list but ember sends it in a param named checklist.
Processing by CheckListsController#update as JSON
Parameters: {"checklist"=>{"name"=>"Kaffeevertrieb", "description"=>""},
"id"=>"3", "check_list"=>{}}
ActionController::ParameterMissing (param is missing or the value is empty: check_list):
Does someone know how to insert the underscore to the json request?
Greetings