0

I have these two arrays:

String[] COLUMN_NAMES = { "row_number", "column_name", "column_value_string", "column_value_float", "blockId", "pipelineId" };
String[] Values = { "1", "Output", "Valid", "", "123sde-dfgr", "pipeline-sde34" };

Where the output I need to be is in a json format (replacing empty values in Values Array with null in the output):

{
    "row_number": 1,
    "column_name": "output",
    "column_value_string": "Valid",
    "column_value_float": null,
    "blockId": "123sde-dfgr",
    "pipelineId": "pipeline-sde34"
}

Here is the code:

Map<String,String> result = IntStream.range( 0,COLUMN_NAMES.length ).boxed()
                                .collect( Collectors.toMap( i->COLUMN_NAMES[i], i->Values[i] ) );
basel.ai
  • 157
  • 2
  • 15
  • 2
    Can you share the code you have used to do this? – BlackHatSamurai Aug 28 '19 at 16:00
  • @Mike'Pomax'Kamermans have you read the rest of the question? I mentioned that the empty values should be replaced with null – basel.ai Aug 28 '19 at 16:03
  • @BlackHatSamurai will do now – basel.ai Aug 28 '19 at 16:03
  • 2
    Build a `Map` of column names to values, replacing empty values with null as you go, then ask a JSON generator to convert that to JSON. – Andreas Aug 28 '19 at 16:03
  • One liner: `JSONObject jSONObject = new JSONObject(IntStream.range(0, COLUMN_NAMES.length).boxed() .collect(Collectors.toMap(i -> COLUMN_NAMES[i], i -> (Values[i] == "" ? null : Values[i])))); ` – Giddy Naya Aug 28 '19 at 16:52

1 Answers1

0
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);
    }
}
i.bondarenko
  • 3,442
  • 3
  • 11
  • 21