How to serialize ANY Object into a URI?

前端 未结 2 1633
长发绾君心
长发绾君心 2020-12-31 09:39

My basic question: is there anything built that already does this automatically (doesn\'t have to be part of a popular library/package)? The main things I\'m working with ar

2条回答
  •  春和景丽
    2020-12-31 10:01

    I think, solution number 4 is OK. It is simple to understand and clear.

    I propose similar solution in which we can use @JsonAnySetter annotation. Please, see below example:

    import com.fasterxml.jackson.annotation.JsonAnySetter;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class JacksonProgram {
    
        public static void main(String[] args) throws Exception {
            C1 c1 = new C1();
            c1.setProp1("a");
            c1.setProp3("c");
    
            User user = new User();
            user.setName("Tom");
            user.setSurname("Irg");
    
            ObjectMapper mapper = new ObjectMapper();
            System.out.println(mapper.convertValue(c1, UriFormat.class));
            System.out.println(mapper.convertValue(user, UriFormat.class));
        }
    }
    
    class UriFormat {
    
        private StringBuilder builder = new StringBuilder();
    
        @JsonAnySetter
        public void addToUri(String name, Object property) {
            if (builder.length() > 0) {
                builder.append("&");
            }
            builder.append(name).append("=").append(property);
        }
    
        @Override
        public String toString() {
            return builder.toString();
        }
    }
    

    Above program prints:

    prop1=a&prop2=null&prop3=c
    name=Tom&surname=Irg
    

    And your getRequest method could look like this:

    public String getRequest(String url, Object obj) {
        String serializedUri = mapper.convertValue(obj, UriFormat.class).toString();
        String response = restTemplate.getForObject(url + "?" + serializedUri, String.class);
        return response;
    }
    

提交回复
热议问题