Reputation: 129
I am making GET request and it has 2 parameters or basically an array
param {
paramNo:1,
from:mobile,
to:server
}
param {
paramNo:2,
from:server,
to:mobile
}
In my controller I have captured it as
public @ResponseBody SearchResponse serverSearch(@RequestParam List<String> param) throws Exception {
ObjectMapper mapper = new ObjectMapper();
List<SearchInfo> searchInfo = mapper.readValue(param,new TypeReference<List<SearchInfo>>(){});
}
mapper.readValue does not take a List. It is throwing compilation error.
Question
Upvotes: 2
Views: 3074
Reputation: 4078
You will have to use arrays instead of lists initially, but you can easily do a: List<SearchInfo> params = Arrays.asList(myArray);
If your parameters are valid JSON, as it seems from your example, it's quite simple to convert into a custom object, see here.
Otherwise you can create a custom formatter with Spring that will format the Strings that come from your request parameters into your custom objects. Basically you'll have to first create a class that registers the type of objects to format and which class does the formatting:
import org.springframework.format.FormatterRegistrar;
import org.springframework.format.FormatterRegistry;
public class SearchInfoFormatterRegistrar implements FormatterRegistrar {
@Override
public void registerFormatters(FormatterRegistry registry) {
registry.addFormatterForFieldType(SearchInfo.class, new SearchInfoFormatter());
}
}
Then implement the class doing the formatting (mind you, this is not just casting an object to a different type, you actually have to use some logic):
import org.springframework.format.Formatter;
public class SearchInfoFormatter implements Formatter<SearchInfo> {
@Override
public String print(SearchInfo info, Locale locale) {
// Format SearchInfo into String here.
}
@Override
public SearchInfo parse(String text, Locale locale) {
// Format String into SearchInfo here.
}
}
Finally, you add them into your configuration:
<bean name="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatterRegistrars">
<set>
<bean class="org.my.SearchInfoFormatterRegistrar" />
</set>
</property>
</bean>
Upvotes: 2