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] ) );
5
  • 2
    Can you share the code you have used to do this? Commented Aug 28, 2019 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 Commented Aug 28, 2019 at 16:03
  • @BlackHatSamurai will do now Commented Aug 28, 2019 at 16:03
  • 2
    Build a Map<String, String> of column names to values, replacing empty values with null as you go, then ask a JSON generator to convert that to JSON. Commented Aug 28, 2019 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])))); Commented Aug 28, 2019 at 16:52

1 Answer 1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.