JAXB/Gson for URL encoded lines
-
Let's say there's a simple POJO:
public class CustomRequest { private String param1; private String param2;
public CustomRequest() { } //getters and setters here
}
Serialyize him in XML, JSON has no problem.
How can you show him to the URL encoded line?I mean, the way out is:
param1=value1¶m2=value2
Interesting existing JAXB, Gson
-
Try to use the annotation.
@JsonAnySetter
(com.fasterxml.jackson.annotation.JsonAnySetter) and classObjectMapper
(com.fasterxml.jackson.databind.ObjectMapper)Example of code:
public class App {
public static void main(String[] args) { CustomRequest cr = new CustomRequest(); cr.setParam1("hello"); cr.setParam2("Привет"); ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.convertValue(cr, MyURLFormatter.class)); }
}
/**
-
Класс для преобразования
-
@author Chubatiy
*/
class MyURLFormatter {public MyURLFormatter() {
}
//билдер для формирования строки
private StringBuilder ulrBuilder = new StringBuilder();/**
- Метод для добавления в uri
*/
@JsonAnySetter
public void add(String name, Object property) {
if (ulrBuilder.length() > 0) {
ulrBuilder.append("&");
}
ulrBuilder.append(name).append("=").append(property);
}
/**
- @inheritDoc
*/
@Override
public String toString() {
return ulrBuilder.toString();
}
}
- Метод для добавления в uri
/**
-
Ваш класс
-
@author Chubatiy
*/
class CustomRequest {private String param1;
private String param2;public CustomRequest() {
}public String getParam1() {
return param1;
}public void setParam1(String param1) {
this.param1 = param1;
}public String getParam2() {
return param2;
}public void setParam2(String param2) {
this.param2 = param2;
}
}
Result:
param1=hello¶m2=Привет
-