Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a Java object to key-value string

I have this Java object and I will like to convert it into a key-value string joined by ampersand.

private String name;
private int age;
private String address;
private String city;

Convert into this key-value string.

name=John&age=30&address=12st NW Street&city=New York

I have tried Jackson but I dont want a JSON string.
I have tried URIEncoder but I don’t need it to be encoded.
Tried looping each property using reflection, but I guess theres a better way.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have considered toString, but I want something more flexible. Because properties name might change.

>Solution :

I would go with the proposition of @Thomas where you can use for example:

ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = mapper.convertValue(person, Map.class);

String response = map.entrySet().stream()
        .map(entry -> String.format("%s=%s", entry.getKey(), entry.getValue()))
        .collect(Collectors.joining("&"));

Outputs

name=John&age=30&address=12st NW Street&city=New York
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading