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&param2=value2

    Interesting existing JAXB, Gson



  • Try to use the annotation. @JsonAnySetter(com.fasterxml.jackson.annotation.JsonAnySetter) and class ObjectMapper(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();
        }
        }

    /**

    • Ваш класс

    • @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=Привет


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2