将字符串数组反序列化为CSV。

huangapple go评论84阅读模式
英文:

Deserialize array of strings to csv

问题

我有一个带有 JSON 负载的数据:

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

如何使用 Jackson 将其反序列化为 CSV 格式,例如:

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

之前我将其反序列化为 `String[]`,但无法与 Hibernate 一起使用,所以现在我想将其反序列化为 CSV 格式。

编辑:

我想使用注解将 JSON 数组转换为一个字符串,其中数组的每个元素由逗号分隔。可能类似于 `@JsonRawValue` 这样的方式。目标是将该值通过 Hibernate 持久化到数据中。
英文:

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.

答案1

得分: 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);	
}

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]
英文:
public static void main(String[] args) {
		String jsonStr = &quot;{\&quot;host_names\&quot;: [\r\n&quot; + 
				&quot;    \&quot;www.host1.com\&quot;,\r\n&quot; + 
				&quot;    \&quot;www.host2.com\&quot;\r\n&quot; + 
				&quot;]}&quot;;
		JSONObject jsonObject = new JSONObject(jsonStr);
		JSONArray hostNames = jsonObject.getJSONArray(&quot;host_names&quot;);
		String result = &quot;&quot;;
		for(int i=0;i&lt;hostNames.length(); i++) {
			if(!result.isEmpty())
			result = result+&quot;,\&quot;&quot;+hostNames.getString(i)+&quot;\&quot;&quot;;
			else
				result = &quot;\&quot;&quot;+hostNames.getString(i)+&quot;\&quot;&quot;;
		}
		System.out.println(result);	
	}

result

&quot;www.host1.com&quot;,&quot;www.host2.com&quot;

Other approach based on annotation

Create a class

class Server{
	
	@JsonProperty(value = &quot;host_names&quot;)
	private List&lt;String&gt; hostNames;

	public List&lt;String&gt; getHostNames() {
		return hostNames;
	}

	public void setHostNames(List&lt;String&gt; 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 = &quot;{\&quot;host_names\&quot;: [\r\n&quot; + 
				&quot;    \&quot;www.host1.com\&quot;,\r\n&quot; + 
				&quot;    \&quot;www.host2.com\&quot;\r\n&quot; + 
				&quot;]}&quot;;
		ObjectMapper mapper = new ObjectMapper();
		Server server = mapper.readValue(jsonStr, Server.class);
		System.out.println(server.getHostNames());
	}

output

[www.host1.com, www.host2.com]

答案2

得分: 0

你可以稍微修改host_names属性的setter / getter,如下所示:

Bean类

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;
    }
}

主方法

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);
}

输出

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

这样你可以在序列化时将其作为逗号分隔的字符串,而在反序列化时将其作为字符串数组。

英文:

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

Bean Class

public class Server {

    @JsonProperty(&quot;host_names&quot;)
    private List&lt;String&gt; hostNames;

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

    @JsonSetter(&quot;host_names&quot;)
    public void setHostNames(List&lt;String&gt; hostNames) {
        this.hostNames = hostNames;
    }
}

Main Method

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

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

Output

{
  &quot;host_names&quot; : &quot;www.host1.com,www.host2.com&quot;
}

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

答案3

得分: 0

另一种使用 @JsonValue 注解的解决方案。将您的 bean 类定义如下:

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;
    }
}

主方法

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);
}

输出

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

此方法仅在您的 bean 类没有其他要序列化的字段时才有用。

英文:

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

public class Server {

    @JsonProperty(&quot;host_names&quot;)
    private List&lt;String&gt; hostNames;

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

    public List&lt;String&gt; getHostNames() {
        return hostNames;
    }

    public void setHostNames(List&lt;String&gt; hostNames) {
        this.hostNames = hostNames;
    }
}

Main Method

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

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

Output

&quot;www.host1.com,www.host2.com&quot;

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

huangapple
  • 本文由 发表于 2020年8月30日 02:07:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63650255.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定