1

I have a json payload with:

"host_names": [
    "www.host1.com",
    "www.host2.com"
]

How can I deserialize this as a csv using Jackson - e.g.:

"www.host1.com,www.host2.com"

Previously I was deserializing this as a String[] but I can't persist that with hibernate, so now I'm trying to deserialize it as a csv.

EDIT:

I want to use annotations to turn the json array into a string, where each element of the array is separated by a comma. Perhaps something like @JsonRawValue. The goal is to then persist the value to a data via hibernate.

3 Answers 3

1
public static void main(String[] args) {
        String jsonStr = "{\"host_names\": [\r\n" + 
                "    \"www.host1.com\",\r\n" + 
                "    \"www.host2.com\"\r\n" + 
                "]}";
        JSONObject jsonObject = new JSONObject(jsonStr);
        JSONArray hostNames = jsonObject.getJSONArray("host_names");
        String result = "";
        for(int i=0;i<hostNames.length(); i++) {
            if(!result.isEmpty())
            result = result+",\""+hostNames.getString(i)+"\"";
            else
                result = "\""+hostNames.getString(i)+"\"";
        }
        System.out.println(result); 
    }

result

"www.host1.com","www.host2.com"

Other approach based on annotation

Create a class

class Server{
    
    @JsonProperty(value = "host_names")
    private List<String> hostNames;

    public List<String> getHostNames() {
        return hostNames;
    }

    public void setHostNames(List<String> hostNames) {
        this.hostNames = hostNames;
    }
}

Now use com.fasterxml.jackson.databind.ObjectMapper to parse the JSON into this class

public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
        String jsonStr = "{\"host_names\": [\r\n" + 
                "    \"www.host1.com\",\r\n" + 
                "    \"www.host2.com\"\r\n" + 
                "]}";
        ObjectMapper mapper = new ObjectMapper();
        Server server = mapper.readValue(jsonStr, Server.class);
        System.out.println(server.getHostNames());
    }

output

[www.host1.com, www.host2.com]
Sign up to request clarification or add additional context in comments.

6 Comments

Is there a way using annotations? Such as JsonFormat?
@eddie-ryan updated my answer , let me know if it works for you.
thanks for the help so far. I'm trying to use annotations to deserialize the string[] in the json to a string (csv). I'm currently using code similar to your approach
what exactly u mean by string csv ? is there any particular format u want , if u can help me to understand the scenario better
@eddie-ryan updated my first approach to get what u want, working on the second to get the same result
|
0

You can slightly modify your setter / getter for host_names property as

Bean Class

public class Server {

    @JsonProperty("host_names")
    private List<String> hostNames;

    @JsonGetter("host_names")
    public String getHostNames() {
        return String.join(",", hostNames);
    }

    @JsonSetter("host_names")
    public void setHostNames(List<String> hostNames) {
        this.hostNames = hostNames;
    }
}

Main Method

public static void main(String[] args) throws JsonProcessingException {

    ObjectMapper mapper = new ObjectMapper();
    Server server = mapper.readValue("{\"host_names\":[\"www.host1.com\",\"www.host2.com\"]}", Server.class);
    String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(server);
    System.out.println(json);
}

Output

{
  "host_names" : "www.host1.com,www.host2.com"
}

This way you can serialize as comma separated string, and array of string while deserializing.

Comments

0

Another Solution using @JsonValue Annotation.
Define your bean class as:

public class Server {

    @JsonProperty("host_names")
    private List<String> hostNames;

    @JsonValue
    public String hostNames() {
        return String.join(",", hostNames);
    }

    public List<String> getHostNames() {
        return hostNames;
    }

    public void setHostNames(List<String> hostNames) {
        this.hostNames = hostNames;
    }
}

Main Method

public static void main(String[] args) throws JsonProcessingException {

    ObjectMapper mapper = new ObjectMapper();
    Server server = mapper.readValue("{\"host_names\":[\"www.host1.com\",\"www.host2.com\"]}", Server.class);
    String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(server);
    System.out.println(json);
}

Output

"www.host1.com,www.host2.com"

This method will only be useful if your bean class has no other fields to serialize.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.