Search code examples
javajacksonspring-validator

How to verify param is actually Json, not just a string


I have a JsonNode that I am accepting as a param to an endpoint. Looks something like this:

@ApiModelProperty(value = "data", example = "{}", required = true)
@NotNull(message = "data cannot be null")
protected JsonNode data;

I want to create a Validator called @ValidJson. The JsonNode itself will make sure that the information being fed to it is valid json, so if I pass something like:

{"data" = "hello",}, where there is an extra comma after the "hello", it will throw an error. But how do I make sure I'm not getting something like "Hello" for JsonNode, which is valid json since a normal String is a valid json representation?

I was thinking at first of checking if the String is just alphanumeric and if it is, then I would consider it invalid, but then obviously someone can just pass a string with a symbol in it and it would be fine. The best solution I could think of was to check that the first and last characters are { and } respectively, and JsonNode would take care of the rest. But I don't know enough about JsonNode, so maybe someone here has a better idea?

Edit:

To be more specific with what I want, here are a couple of examples:

JsonNode will take care of incorrect Json. I want to do some stricter verification on the data I get in. I don't want to receive any sort of Json, I want the "real", serializable json that we all mean when we say json. If a user passes a string that looks like:

"Hello" "Hello world" "I'm just a random String that isn't in a key:value structure"

Etc, I want to throw an error and ask them for Json formatted in key:value structure like:

{
   "key": "value"
}

I was thinking of checking to see if the first and last string values are { and } respecitvely, as I mentioned in my comments, but I think that's too "hacky" and there could perhaps be a better method.


Solution

  • As @VinceEmigh pointed out in the comments, isObject is the function I was looking for.