I am trying to return some JSON from a WCF service. This service simply returns some content from my database. I can get the data. However, I am concerned about the format of my JSON. Currently, the JSON that gets returned is formatted like this:
{"d":"[{\"Age\":35,\"FirstName\":\"Peyton\",\"LastName\":\"Manning\"},{\"Age\":31,\"FirstName\":\"Drew\",\"LastName\":\"Brees\"},{\"Age\":29,\"FirstName\":\"Tony\",\"LastName\":\"Romo\"}]"}
In reality, I would like my JSON to be formatted as cleanly as possible. I believe (I may be incorrect), that the same collection of results, represented in clean JSON, should look like so:
Sucess([{"Age":35,"FirstName":"Peyton","LastName":"Manning"},{"Age":31,"FirstName":"Drew","LastName":"Brees"},{"Age":29,"FirstName":"Tony","LastName":"Romo"}])
can anyone please suggest me how could i achive this or let me correct if I am doing something wrong.
It normally depends on what and how you are returning data from JSON. If you are returning String then it might contain / in your string.
But if you are sending custom data, then it will be clean JSON. For example:
[DataContract(Namespace = "")]
public class MyData
{
private int age;
private String firstName;
private String LastName;
[DataMember]
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
//Apply same for other members
}
And suppose this is your operation contract.
MyData getData();
Hope, this will work.
Related
i have a use case where the user can send following params with get request
GET localhost/8080/users?filter=alex
OR
GET localhost/8080/users?suffixFilter=lex
OR
GET localhost/8080/users?prefixFilter=a
is it possible to add only one request param instead of 3 in controller
e.g.
instead of
#GetMapping("/users")
#ResponseBody
public String getFoos(#RequestParam String filter, #RequestParam String prefixFilter , #RequestParam String suffixFilter) {
return "ID: " + id;
}
is it possible to create a dynamic one which includes those three variantes? I was thinking creating class like this
public class FilterCreteria {
private String filter;
private String suffixFilter;
private String prefixFilter;
}
and then passing this to controller
#GetMapping("/users")
#ResponseBody
public String getFoos(#RequestParam FilterCreateria filter) {
return "ID: " + id;
}
the problem is if i send filter=alex the other attributes in the class FilterCreteria is null and i want to avoid this null.
What i searching for:
is there other way of making this possible?
if my suggestion is ok, how to avoid null attributes when the user only sends one queryparam like filter=alex?
I need to consume this API: https://api.punkapi.com/v2/beers and after consuming, I have to store it in the database, but only with next fields: internal id, name, description and mean value of the temperature. Any ideas or advice?
The simplest approach would be to have your Model only containing those attributes so that Spring only deserialize them from JSON to object. Something like the following:
public class YourModel {
private long id;
private String name;
private String description;
}
Then in your Service you would have:
ResponseEntity<YourModel> response = restTemplate.getForEntity(url, YourModel.class);
You can then either save YourModel directly to the database (first you need to add some #Annotations if you want to rely on JPA) or you may build another more suited model to your use case.
I am new to Spring Rest. While Doing POST, we have 2 options either #RequestBody or #RequestParams.
My query is not what they are. I am pretty well know what they are.
Normally we use #RequestParams for form-urlencoded and #RequestBody for JSON/XML.
I have a scenario as below:
class EmployeeDTO {
long id;
String name;
String age;
String address;
String salary;
//Getters and Setters
}
For POST, I can directly use as void doSomething(#RequestBody EmployeeDTO){ }
and also I can do same thing but using 5 RequestParams
void doSomething(#RequestParam(id) long id, #RequestParam(name) String name, #RequestParam(age) String age, #RequestParam(address) String address, #RequestParam(salary) String salary){ }
I have seen some good sites like Stripe, they following only #RequestParam in their REST Api.
I actually got to understand that we use RequestBody for Complex Input and#RequestParam for simple parameters.
So, my actual query is: In above class, had only 5 parameters, I am thinking its okay going with #RequestParam, But what if there are like 7 or 10 input params, then should I chose RequestBody or (7 or 10) REquestParam?
EDIT:
class Orders {
String id;
Employee employee;
}
It is not really a choice based on "number of data I have to push on server".
Historically and in general the use of the query string is, as the name implies, to query data. And so request param would be the preferred choice when you want to "pull" data HTTP GET
Here if the goal is to "push" data on the server (for instance "to create an employee") you should prefer sending this data in request body.
Moreover the query string is part of the URL, and it can be read by everyone sitting between the clients and the API, so we shouldn’t put sensitive data like passwords into the query string.
you can mimic the format of query string in your body by using the mime type application/x-www-form-urlencoded. Here request body uses the same format as the query string.
parameter=value¶meter2=another
I am trying to Map a JSON response to a Java POJO which has a different field name from different API.
I need an efficient way to do this reducing boilerplate codes.
I have tried mapping the JSON property field in Java POJO.
However, the problem is I am fetching data from different sources.
Let's say I have below user class
Class User{
String name;
String contact;
}
The JSON I may receive from different sources can be
{"name": "ABC" , "contact": "123456"}
or
{"userName": "XYZ" , "mobileNo":"4354665"}
There may be more variations as we go on integrating more API's
Is there a way I can archive this?
above is just a simple example
there could be more complex JSON object I may need to read.
like List of User etc.
You can use the #JsonAlias() to give the variable more than one JSON key binding.
#JsonAlias is introduced in Jackson 2.9 release. #JsonAlias defines one or more alternative names for a property to be accepted during deserialization i.e. setting JSON data to Java object. But at the time of serialization i.e. while getting JSON from Java object, only actual logical property name is used and not alias. #JsonAlias is defined as follows.
#Entity
Class User{
#JsonProperty()
#JsonAlias({"name", "userName"})
String name;
#JsonProperty()
#JsonAlias({"contact", "mobileNo"})
String contact;
}
You could use the #JsonSetter annotation like :
public class User{
public String contact;
public String name;
#JsonSetter("name")
public void setName(String name) {
this.name = name;
}
#JsonSetter("userName")
public void setName(String name) {
this.name = name;
}
}
Instead of directly mapping to an entity class , you should have a DTO object or model in between to map the json response. Then, you can convert that into any entity you may choose.If you are fetching the data from different sources , it means you are calling different endpoints, why don't you create different DTO 's for that.In that way even if one of the endpoints introduce a change , it won't affect the rest of the endpoint calls.
Vice-versa you could have different DTO objects being returned from the two endpoints instead of returning the same Entity class as well, that way you can have control over which attributes should be there in the response.
To reduce the boiler plate code, you could use library such as MAP STRUCT to enable conversion between entity and DTO objects easily
Read here about the advantages of using a DTO .
I am using Retrofit and Gson to query an API, however I have never come across a JSON response like it.
The Response:
{
Response: {
"Black":[
{"id":"123","code":"RX766"},
{"id":"324","code":"RT344"}],
"Green":[
{"id":"3532","code":"RT983"},
{"id":"242","code":"RL982"}],
"Blue":[
{"id":"453","code":"RY676"},
{"id":"134","code":"R67HJH"}]
}
}
The problem is the list elements id eg "black" is dynamic, so I a have no idea what they will be.
So far I have created a class for the inner type;
class Type {
#SerializedName("id") private String id;
#SerializedName("code") private String code;
}
Is it possible to have the following?
class Response {
#SerializedName("response")
List<Type> types;
}
And then move the list ID into the type, so the Type class would become;
class Type {
#SerializedName("id") private String id;
#SerializedName("code") private String code;
#SerializedName("$") private String type; //not sure how this would be populated
}
If not, how else could this be parsed with just Gson attributes?
Ok so I have just seen this question;
How to parse dynamic JSON fields with GSON?
which looks great, is it possible to wrap a generic map with the response object?
If the keys are dynamic you want a map.
class Response {
#SerializedName("response")
Map<String, List<Type>> types;
}
After deserialization you can coerce the types into something more semantic in your domain.
If this is not suitable you will need to register a TypeAdapter or a JsonDeserializer and do custom deserialization of the map-like data into a simple List.