I want to create a json object with values of "3D Tour", "Videos", "Photos Only", etc. You can find the enum class below. How can I implement that?
package com.padgea.listing.application.dto;
public enum General implements Catalogue {
Tour("3D Tour"),
Videos("Videos"),
Photos_Only("Photos Only"),
Price_Reduced("Price Reduced"),
Furnished("Furnished"),
Luxury("Luxury");
private final String value;
General(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
I need a output like this {General : "3D Tour","Videos","Photos Only",etc}
CodePudding user response:
This will return a list of strings containing all the values.
enum General implements Catalogue {
Tour("3D Tour"),
Videos("Videos"),
Photos_Only("Photos Only"),
Price_Reduced("Price Reduced"),
Furnished("Furnished"),
Luxury("Luxury");
private final String value;
General(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static List<String> valuesList() {
return Arrays.stream(General.values())
.map(General::getValue)
.collect(Collectors.toList());
}
}
And a level up you'll do something like
myJson.put("General", General.valuesList())
An output will be
{
"General": ["3D Tour","Videos","Photos Only"]
}
CodePudding user response:
The valid JSON would look like this
{
"General": ["3D Tour","Videos","Photos Only"]
}
If you would use Jackson library for creating your JSON you would need to create a class like this:
public class GeneralDTO {
@JsonProperty("General")
private String[] general;
...
}
Then you would need to create your GeneralDTO object.
You can get all your enum values in an array like this
String[] generalArray = Arrays.stream(General.values())
.map(st -> st.getValue())
.toArray(String[]::new);
Then using the method writeValueAsString
of ObjectMapper
class (part of Jackson library) you can get JSON string from your GeneralDTO
object.
To simplify you can use Map<String, String[]>
instead of GeneralDTO
Map<String, String[]> generalObject = new HashMap<>;
generalObject.put("General", generalArray);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(generalObject);