This question already has answers here:
How to merge two arrays into a map using Java streams?
(2个答案)
在10个月前关闭。
我有这两个数组:
我需要的输出是json格式(将Values Array中的空值替换为输出中的null):
这是代码:
(2个答案)
在10个月前关闭。
我有这两个数组:
String[] COLUMN_NAMES = { "row_number", "column_name", "column_value_string", "column_value_float", "blockId", "pipelineId" };
String[] Values = { "1", "Output", "Valid", "", "123sde-dfgr", "pipeline-sde34" };
我需要的输出是json格式(将Values Array中的空值替换为输出中的null):
{
"row_number": 1,
"column_name": "output",
"column_value_string": "Valid",
"column_value_float": null,
"blockId": "123sde-dfgr",
"pipelineId": "pipeline-sde34"
}
这是代码:
Map<String,String> result = IntStream.range( 0,COLUMN_NAMES.length ).boxed()
.collect( Collectors.toMap( i->COLUMN_NAMES[i], i->Values[i] ) );
最佳答案
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) throws JsonProcessingException {
String[] COLUMN_NAMES = { "row_number", "column_name", "column_value_string", "column_value_float", "blockId", "pipelineId" };
String[] Values = { "1", "Output", "Valid", "", "123sde-dfgr", "pipeline-sde34" };
Map<String, String> map = new LinkedHashMap<>();
for (int i = 0; i < COLUMN_NAMES.length; i++) {
map.put(COLUMN_NAMES[i], Values[i]);
}
String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);
}
}
关于java - 将两个字符串数组合并为JAVA中的JSON格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57696213/