Home > Enterprise >  How to convert a Java object to key-value string
How to convert a Java object to key-value string

Time:01-13

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.

CodePudding user response:

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

CodePudding user response:

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;
}
  •  Tags:  
  • java
  • Related