有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在JAVA中将两个字符串数组合并为JSON格式

我有两个阵列:

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格式(将值数组中的空值替换为输出中的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] ) );

共 (1) 个答案

  1. # 1 楼答案

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