List of Enum in Json Java - java

I want to send a request to my controller via Postman and I actually don't know the structure of a list containing Enum class
I'll give an example of a Enum to make it easy to explain:
public enum ReservationState {
WAITING("Waiting"),
BUSY("Busy"),
READY("Ready");
private String status;
public ReservationState(String status){
this.status = status;
}
}
So how does a List<ReservationState> reservations look in a json string?
Thanks in advance!!

Try this {"reservations": ["WAITING", "BUSY", "READY" ]}

{
"reservations": [
"WAITING",
"BUSY",
"READY"
]
}
unless you provided special serializer, enums are serialized as their enum literals

Related

Can I have an Avro Schema with an enum that includes values as enum members?

This is the Java enum that I want to transform into an Avro Schema:
public enum ApplicationCode {
APP_A("MY-APP-A"),
APP_B("MY-APP-B");
private final String code;
ApplicationCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
Since enums are generally available as Types in Avro, I came up with following:
{
"type" : "enum",
"name" : "ApplicationCode",
"namespace" : "com.example",
"symbols" : [ "APP_A", "APP_B" ]
}
And referenced it in my main Avro like this:
"fields": [
{
"name": "masterApplicationCode",
"type": "ApplicationCode"
},
It works like that but unfortunately I am losing the Application Codes (e.g. "MY-APP-A") using this approach. I'm looking for something, that allows me to include both, the code and the label. Something like
{
"type" : "enum",
"name" : "ApplicationCode",
"namespace" : "com.example",
"symbols" : [ "APP_A("MY-APP-A")", "APP_B("MY-APP-B")" ]
}
Is it even possible to have this kind of complex enums or is there any workaround to achieve this?
I believe the avro schema is internally transforming it into a JSON String. So, I think the question is more about serializing enums. Reference from here - https://www.baeldung.com/jackson-serialize-enums
I think it should return the code if you use JsonFormat annotation like this -
#JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum ApplicationCode {
Otherwise you will need to add a Custom Serializer for enum.
I solved my problem by writing custom serializer / deserializer that map an object with complex typed fields to one that is being sent with e.g. Strings instead of enums.
Here an example of the custom serializer:
public class CustomSerializer implements Serializer<ApplicationObject> {
#Override
public byte[] serialize(String topic, ApplicationObject ApplicationObjectDto) {
com.example.avro.ApplicationObject applicationObject = com.example.avro.ApplicationObject.newBuilder()
.setApplicationCode(ApplicationObjectDto.getApplicationCode().getCode())
.build();
return SerializationUtils.serialize(applicationObject);
}
}

Graphql to accept list of user defined objects

I have a requirement where i have to accept the list of objects.
The method in mutation class looks like this
#GraphQLMutation //1
public void ack(#GraphQLInputField List<PingEntity> pingEntityList) { //2
log.info("Handling ack calls.");
pingEntityRepository.savePingEntityList(pingEntityList);
}
PingEntity looks like this
#Data
//#Document(collection="pingdatastore")
#AllArgsConstructor
#NoArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = true)
public class PingEntity {
private String id;
#JsonProperty("action")
private String action;
#JsonProperty("message")
private String message;
#JsonProperty("timestamp")
private Long timestamp;
#JsonProperty("transactionId")
private String transactionId;
#JsonProperty("type")
private Integer type;
private String imei;
}
my query looks like this
mutation ack {
ack(pingEntityList: [{action: "KEEP-ALIVE2", message: "Keep alive message at regular intervals", timestamp: 1462747047}]) {
id
}
}
I got the Error like this:
"data": null,
"errors": [
{
"validationErrorType": "SubSelectionNotAllowed",
"message": "Validation error of type SubSelectionNotAllowed: Sub selection not allowed on leaf type Boolean",
"locations": [
{
"line": 2,
"column": 3
}
],
"errorType": "ValidationError"
}
]
}
I tried giving different annotations. i am not able to solve this issue.. need help in this issue
Thanks in advance :)
The problem seems to be that your ack method returns void which gets mapped to boolean, for the lack of a better option. As boolean is a simple scalar, you can not select anything from it, and you're trying to select an id in the query.
If you'd change your ack method to return the saved List<PingEntity>, you'd get the behavior you wanted.
But... more importantly, what library are you using, as the annotations I see (#GraphQLInputField) in your code are not from graphql-java (as graphql-java itself provides no annotations), nor from any of the libraries I recognize.
It seems to be coming from a really old and never publically released version of graphql-spqr. If this is indeed the case, you absolutely need to update to the latest as the version you seem to be using was alpha quality at best.

Exclude a value in JSON object when passing as request to API based on condition

i want to exclude a value from JSON Object when passing as input to an API based on the condition. i.e for some scenario that partcular key:value is not requried ,but for some that key:value is need .
Input JSON is as Below
{
"customerNumber" : "6634374019",
"ea" : "",
"source" : "Test",
"dataCentre" : "US",
"requestId" : "CSP-QA-1574"
}
and Class for above is as follows
public class order
{
#JsonProperty(value="customerNumber")
public String customerNumber;
#JsonProperty(value="ea")
public String ea;
#JsonProperty(value="source")
public String source;
#JsonProperty(value="dataCentre")
public String dataCentre;
#JsonProperty(value="requestId")
public String requestId;
//constructor for assiging data
//getters and setters
}
Can any body please help me in this. i do not want to pass "ea" key:value in JSON input for some scenarios and in some i need to pass. how to achieve this.
thnaks in advance
Use:
#JsonIgnore
And be happy.
Cheers
If I had to do this then I would have gone with a slightly different approach.
JsonObject gsonObject=new JsonObject();
gsonObject.addProperty("ea","value");
like that conditionally addProperty().
Since I don't have enough rep So I am putting it like answer instead of comment
You can use #JsonIgnoreProperties on class level if you want to ignore any values that are not passed. If you want to ignore a single value, you can use #JsonIgnore at member level.
#JsonIgnoreProperties({"Ignore 1", "Ignore 2"})
class Sample {
or
class Sample {
private String xyz;
#JsonIgnore
private String ignorethis;

Parse JSON without object name in Java

I am trying to parse this JSON which is coming as the response to a REST API call. Can you please help me parsing it as key value pairs?
The object names are not present. There is nesting as well. There seems to be no new line between records.
The aim is to extract this data and load it into a database.
[
{
"cc_emails":["feedback#xyz.com"],
"fwd_emails":[],
"reply_cc_emails":["feedback#xyz.com"],
"fr_escalated":false,
"spam":false,
"email_config_id":6000038087,
"group_id":6000110481,
"priority":1,
"requester_id":6010410791,
"responder_id":6002817857,
"source":1,
"company_id":null,
"status":2,
"subject":"fare",
"to_emails":["feedback#xyz.com"],
"product_id":null,
"id":45043,
"type":null,
"due_by":"2016-03-12T08:58:02Z",
"fr_due_by":"2016-03-08T08:58:02Z",
"is_escalated":false,
"description":"Dear xyze Team,\r\n\r\nWhy r u increased fair again and againasas0mail.gmail.com</a>.<br>\n",
"custom_fields":
{
"category":null,
"issue":null,
"route_id":null,
"phone_number":null,
"department":null,
"booking_id":null
},
"created_at":"2016-03-07T08:58:02Z",
"updated_at":"2016-03-07T08:58:03Z",
// ...... repeat
}
]
The best way to do this would be to use http://www.jsonschema2pojo.org/
Enter your json there
Change source type to JSON
set the correct class name and package.
The resulting pojo can be directly mapped from the json
If you are using resttemplate to hit the api then you can use getForObject to automatically set the pojo from the output.
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#getForObject-java.lang.String-java.lang.Class-java.lang.Object...-
Using gson you can do this quite simply.
Do a class to match the fields in the json something like:
public class Example {
private List<String> cc_emails;
private List<String> fwd_emails;
private List<String> reply_cc_emails;
private Boolean fr_escalated;
private Boolean spam;
private Integer email_config_id;
...
private CustomFields custom_fields;
private String created_at;
private String updated_at;
}
Then you need to do another to map the custom fields
public class CustomFields {
private String category;
...
}
And using json you can parse it like this:
Type type = new TypeToken<Collection<Example>>(){}.getType();
new Gson().fromJson(json,type);
You have to exaplain to Gson it's a list, if it was a single object it would be this:
new Gson().fromJson(json,Example.class);
This is the aproach I usually take, also in the dates java.sql.Timestamp class might also parse it, you would need to try it though.
You can use Gson (https://github.com/google/gson) or Jackson (https://github.com/FasterXML/jackson) and deserialize it to a Map.

Gson - Conditional JSON Deserialization (Sanity Checks)

I have code in my android project that correctly deserializes json into POJO's using gson. I wish to add some condtional acceptance checks (sanity checks) to the incoming json. For instance, with the data structure below, I wish for the gson parser to only add objects where the start date < end date. I know I could iterate through the list after it is populated to remove invalid items, but I was wondering if there was any way to reject the items on the fly. Any help would be appreciated.
Example JSON
{
"Items" : [
{
"Name" : "Example Name",
"Start" : "2010-10-16 10:00:00",
"End" : "2011-03-20 17:00:00",
<other fields>
},
<several more items>
]
}
ItemList.java
public class ItemList {
private List<ItemHeader> Items;
public void setItemHeaders(List<ItemHeader> headers) {
Items = headers;
}
public List<ItemHeader> getItemHeaders() {
return Items;
}
}
ItemHeader.java has fields for name, start, end and all the other fields.
You'd need to write your own deserializer and have it throw an exception when your condition isn't met.
http://sites.google.com/site/gson/gson-user-guide#TOC-Writing-a-Deserializer
I don't know that you should do this, but it's possible.

Categories