简体   繁体   中英

How to Convert array of CSV formatted Strings into an array of JSON objects

My code as follows:

private static JsonArray convertExternalLeadDataToJson(String input[]) {
    JsonArray output = new JsonArray();

    // Loop through each CSV row in array
    for (int i = 0; i < input.length; i++) {
        // Split CSV row into separate fields
        List items = Arrays.asList(input[i].split(","));

        // Add fields to JSON object
        JsonObject lead = new JsonObject();
       
        
          lead.add("firstName", items.get(0)); 
          lead.add("lastName", items.get(1)); 
          lead.add("email", items.get(2)); 
          lead.add("title", items.get(3));
         
        output.add(lead);
    }
    return output;
}

For this I am getting error as "The method add(String, int) in the type JsonObject is not applicable for the arguments (String, Object)".

Can anyone help to resolve this issue?

Thanks.

You can use JsonObjectBuilder , it helps to create a Json object.

JsonBuilderFactory factory = Json.createBuilderFactory();
for (int i = 0; i < input.length; i++) {
        // Split CSV row into separate fields
        List items = Arrays.asList(input[i].split(","));

        // Add fields to JSON object
        JsonObject lead = factory.createObjectBuilder()
            .add("firstName", items.get(0))
            .add("lastName", items.get(1))
            .add("email", items.get(2)) 
            .add("title", items.get(3))
            .build();
         
        output.add(lead);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM