Home > Software engineering >  How to convert JSON in QueryParams into Object in Java Spring?
How to convert JSON in QueryParams into Object in Java Spring?

Time:01-24

I have this query

http://localhost:8555/list/csv?search={}

Where search is a json object (omitted other params as they are irrelevant here). How can i convert this into a nested object?

public record CsvParams<T>(
    T search,
    /* Other query params */ ) {}

Right now im getting error that string cannot be cast into object.

class java.lang.String cannot be cast to class classname

Is there anyway to do this? Old solution uses ObjectMapper to convert string into corresbonding object. I was hoping that maybe there is a way to do it more simpli and remove this boilerplate.

CodePudding user response:

Any single value of a query param can't be automatically converted to a non-primitive type. You can convert multiple params to a class, but not one that happens to be a JSON AFAIK. But you can create a converter custom deserialiser and then use it in different controllers, but in the end you'd still use an ObjectMapper.

More info on how to do the latter here: https://www.baeldung.com/spring-mvc-send-json-parameters

CodePudding user response:

If you have to work with query params than I don't think you can have it converted automatically by Spring boot. But if you work with POST or PUT methods and can pass your params as request params in request body your JSON params can be automatically converted to class instances by Spring boot and no effort required from you. However, if you have to work with query param (say you have to use method GET so you have no request body) than you can use Json-Jackson library or Gson library to parse your Json into class instance. If you use Jackson you will need to use class ObjectMapper. For Jackson lib info see this site, for ObjectMapper class see Javadoc here. However, I wrote my own JsonUtils that is very good for simple usecases like yours. It allows to to parse simple JSON into a class with a single method. It is very simple and strait forward. It is a thin wrapper over Jackson library. See the Javadoc for method readObjectFromJsonString. Class JsonUtils is part of Open Source MgntUtils library. You can get it as Maven artifact on Maven Central and as a jar (with source code and Javadoc) on Github

  • Related