Deserialize json to java using jackson - issues with special characters - java

I am using jackson (jersey and jetty) for my REST webservices - and all is going well. But I have a requirement to include a special character in one of the name value pairs in json post request. i.e.
json request (in post body)-
{
"id": "1",
"print-color" : "red"
}
//"-" in "print-color" is giving problems.
Now inside my corresponding java bean for this object Item.java class, I cant make a property with name print-color (because "-" is not allowed). How do I deal with it in mapping?
Thanks.

You could try following in Java POJO:
#JsonProperty("print-color")

Related

Spring boot OpenAPI Swagger enums with empty strings generates "__EMPTY__" instead of ""

I am trying to generate swagger on a spring boot rest service, with the following sample schema.
{
"title": "HouseholdOperationsRequest",
"type":"object",
"properties": {
"operation": {
"type": "string",
"enum": ["Electrical","Plumbing","Paint","Handyman",""]
}
}
}
When testing directly (hitting the server), the validation works fine with an empty string sent in the request. However, the swagger that is generated from this represents the empty enum at the end as "__EMPTY__" and causes a validation failure for the clients sending the request with the operation value as "".
Is there a setting with swagger that can help get around this problem?
Edit: --removing Is it a bad practice using empty string in the enum.--
My requirement is a bit unusual since the downstreams treat nulls differently than empty strings. The field itself is not required and is nullable.
In my opinion, it's not good to have Empty Strings in Enum, rather you should keep this field as Optional in Swagger (if not already), so user can send Null value in that case.
Enum are generally a Group Of Constants and Empty String is not a constant. Rather it should be replaced with Null value in general.

include_in_all setting in spring data elasticsearch

According to Elasticsearch documentation it is possible to exclude a field from _all field using include_in_all setting (set to false). I need to exclude a field from _all and I'm using spring data elasticsearch do define my mappings. I haven't found a way to do it this way.
Is this possible using spring data elasticsearch annotations?
Unfortunately, Spring Data Elasticsearch cannot do this thing. The improvement request is already a year old, but its priority is minor, so there is no hope for now:
https://jira.spring.io/browse/DATAES-226
In my last project I had to do a lot of simple searches (instead of one by "_all" fields, I used 1 search per each field), and then I united all the results. I assume that there is no nice solve for that problem by Spring Data Elasticsearch.
You can save the mapping of your type into a json file. Then you add the '"include_in_all": false' to the field you want to exclude. This should look something like this.
{
"my_type": {
"properties": {
"excludedField": {
"type": "text",
"include_in_all": false
}
}
}
}
Then you load the file using your favorite JSON reader, parse it as a string and change your mapping with the elasticsearch api .
client.admin().indices()
.preparePutMapping("my_index")
.setType("my_type")
.setSource(loadedFileString)
.get();
EDIT: I just noticed you wanted to use annotations for it. Maybe the #Field annotation has a parameter for it? I'm sorry, I have no experience with the annotations.

Jersey - Moxy returning appended json in class property

I have a Jersey client that makes a call to a 3rd party rest api and retrieves some JSON.
{"A":1,"W":2,"List":[{"name":"John","amount":10.0}]}
After that I need to append this JSON to my response class and give it back in the response.
#XmlRootElement
public class MyResponse {
private JsonObject body;
private String status;
I manage to assign the value that comes from the 3rd party api to body but the response that's sent is like this:
{
"status": "success",
"body": {
"entry": [
{
"key": "A",
"value": 1
} ,
{
"key": "W",
"value": 2
},
{
"key": "List",
"value": "[{\"name\":\"John\",\"amount\":10.0}]"
}
]
}
}
So there are two main issues, moxy is generating key and value elements while I would like it to be key: value and also it is not generating properly the 2nd level objects in the JSON structure provided by the API.
MOXy is a JAXB implementation, while JsonObject is part of JSON-P. MOXy happens to be able to deal with JSON too, but that is a proprietary extension over the JAXB standard. As far as I know, there is no default mapping available between JSON-P and JAXB. The reason you're seeing those key/value entries must be because JsonObject extends java.util.Map, so you get the default MOXy mapping for that type.
I think you have the following possibilities:
Go with either JSON-P or JAXB/MOXy (MOXy required for its additional JSON binding) only.
Use one of the JAXB/MOXy mechanisms for mapping custom types from/to JAXB. The standard way is to use an XmlAdapter, examples for dealing with Maps in particular are here and here. But I think this will be difficult if you don't know the structure of the 3rd party JSON content and want to keep nested levels intact.
Yet another possibility might be to use a proprietary API like Jackson, but I can't help with that.

Check if JSON is valid in JAVA using Jackson

I have a JSON string which I am storing it in DB as a string. In front-end, I am rendering this JSON as object.
I am using:
JSON.parse(string);
Uncaught Syntax error: Unexpected Token
String :
{
"id": "295cd59f-4033-438c-9bf4-c571829f134e",
"from": "Shrisha S.<shrisha#s.com>",
"to": [
"Katie Porter <katie.porter#ss.com>"
],
"cc": [
"Jack d<jack.d#dd.com>, Keerthi<keerthi.s#dd.com>"
],
"bcc": [
]
}
Is there any way I can check If JSON is valid or not in JAVA?
One thing to be noted here is that, I don't have a schema defined for JSON which I can map to, i.e. JSON can hold anything.
I am currently trying out with JACKSON but for that I need a pre-defined schema which I don't have. Is there anyway this can be fixed?
You can read it as a JsonNode, no need to map it to a specific Class, its generic:
try{
ObjectMapper objectMapper = ...;
JsonNode jsonNode = objectMapper.readTree(yourJsonString);
} catch(JsonProcessingException e){........}
There are two different parts to the question. First is whether it is valid JSON, and second whether it contains specific set of information.
#pdem already answered first part (you can also read JSON as java.lang.Object to get the same effect).
But for second part, JSON Schema is not usually a good way, as it focuses on JSON aspects but not on more meaningful part of actual data, possible sub-typing and so on, which matter at Java level where all actual data processing occurs.
So usually you would define a POJO (or ideally just use one you use for actual data processing), bind to it (with ObjectMapper.readValue()), and then check whether data is not only technically valid wrt low-level data types, but also that it conforms to additional business constraints.
For latter part you can either write Java code, or use an annotation based framework such as Bean Validation API (JSR-303); see for example:
http://beanvalidation.org/
plus there are many #bean-validation tagged questions here as well related to usage. Some frameworks add explicit support for it; for example the best Java service framework, DropWizard does this. Others like Spring Boot have support as well.
JSON specification forbids it from using newline characters, make sure you are replacing newline characters see
Regex replace all newline characters with comma
make sure you do this before storing it in DB.
public boolean isValidJson(final String json) {
try {
final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode jsonNode = objectMapper.readTree(json);
return jsonNode instanceof ContainerNode;
} catch (JsonProcessingException jpe) {
return false;
}
}

JAX-RS: Is there a serializer for json for root element, part of a list, param in Web service

At the moment I'm designing a RESTful API and use JAX-RS for the backend. Many reponses have the following simple form:
{
"someList": [
"item1" : ...,
"item2" : ...,
"itemn" : ...
]
}
The important thing is the field name of the array. It's required by the client (EmberJS Data). I try to create the responses with the standard ResponseBuilder, but I don't know how to define a field name for the list. All responses I get look like:
[
"item1" : ...,
"item2" : ...,
"itemn" : ...
]
In the past I just always created a container class with one property for the list. That works, but I think there must be a better solution. Maybe a helper class to envelope other objects?
This is depending on the JSON-Serializer you are using. Jettison is wrapping the response in a root-element per default (I don’t think EnvelopeObject is a correct word for this).
If you are using Jackson you can configure this behavior with SerializationFeature.WRAP_ROOT_VALUE (or DeserializationFeature).
The name of the key can be specified with #JsonRootName if you are using Jackson-Annotations or #XmlRootElement if you are using JAXB-Annotations.

Categories

Resources