feco
feco

Reputation: 4424

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.

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

Upvotes: 0

Views: 1575

Answers (2)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59988

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

Upvotes: 1

user19443549
user19443549

Reputation:

You can override the toString() function to get required format -

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

@Override
public String toString() {
    return "name=" + name +
            "&age=" + age +
            "&address=" + address +
            "&city=" + city;
}

Upvotes: 0

Related Questions