Suppose there is a simple POJO:

public class CustomRequest { private String param1; private String param2; public CustomRequest() { } //getters and setters here } 

Serialize it in XML, no JSON problem. How can it be serialized into a URL encoded string?

Those. so that the output was:

 param1=value1&param2=value2 

Interested in existing solutions / frameworks like JAXB, Gson

    1 answer 1

    Try using the @JsonAnySetter annotation (com.fasterxml.jackson.annotation.JsonAnySetter) and the ObjectMapper class (com.fasterxml.jackson.databind.ObjectMapper)

    Code example:

     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(); } } /** * Ваш класс * * @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&param2=Привет 
    • It works, thanks. Back from param1 = hello & param2 = Hi in CustomRequest possible? - Russtam
    • Unfortunately I will not tell you. The only thing that comes to mind is to convert the resulting string to a full json object (ie, param1=hello¶m2=Привет to {"param1":"hello","param2":"Привет"} ) and then the same method ( mapper.convertValue(json, CustomRequest.class) ) to class - Chubatiy
    • Thanks again. Apparently you have to file something with Blackjack and annotations) - Russtam