For such a trivial example, it's pretty easy to produce a poorly-formed JSON String of your content and let JSONObject patch it up.

In a single expression:

new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|1:$2,")))
// {"art":0,"comedy":0,"action":0,"crime":0,"animals":0}

If you really want to keep the 0.0 as Strings:

new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|1:\"$2\",")))
// {"art":"0.0","comedy":"0.0","action":"0.0","crime":"0.0","animals":"0.0"}

If you want to account for possible extraneous whitespaces:

new JSONObject(String.format("{%s}", str.replaceAll("([^,]+)\\s*?,\\s*?([^,]+)(,|1:$2,")))

.. will work with inputs like "art, 0.0, comedy, 0.0, action, 0.0, crime, 0.0, animals, 0.0" and other cases.


Disclaimer: it's not crazy-sexy code but drop in a one-line comment and it could be reasonable so long as the data structure stays simplistic.

Answer from ccjmne on Stack Overflow
Top answer
1 of 3
4

For such a trivial example, it's pretty easy to produce a poorly-formed JSON String of your content and let JSONObject patch it up.

In a single expression:

new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|1:$2,")))
// {"art":0,"comedy":0,"action":0,"crime":0,"animals":0}

If you really want to keep the 0.0 as Strings:

new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|1:\"$2\",")))
// {"art":"0.0","comedy":"0.0","action":"0.0","crime":"0.0","animals":"0.0"}

If you want to account for possible extraneous whitespaces:

new JSONObject(String.format("{%s}", str.replaceAll("([^,]+)\\s*?,\\s*?([^,]+)(,|1:$2,")))

.. will work with inputs like "art, 0.0, comedy, 0.0, action, 0.0, crime, 0.0, animals, 0.0" and other cases.


Disclaimer: it's not crazy-sexy code but drop in a one-line comment and it could be reasonable so long as the data structure stays simplistic.

2 of 3
2

You should use Map instead of Array (List of key/value pair is Map, not Array).

1 way: Using JsonObject

String [] arrayStr=strVal.split(",");
JsonObjectBuilder builder = Json.createObjectBuilder()

String key = null;
for (String s: arrayStr){
    if(key == null) {
       key = s;
    } else {
       builder.add(key, s);
       key = null;
    }
}
JsonObject value = builder.build();

2 way: Using Map

String [] arrayStr=strVal.split(",");
Map<String,String> map = new HashMap<>();

String key = null;
for (String s: arrayStr){
    if(key == null) {
       key = s;
    } else {
       map.put(key, s);
       key = null;
    }
}

// convert Map to Json using any Json lib (Gson, Jackson and so on)
🌐
JBoss.org
developer.jboss.org › thread › 262563
convert a comma separated string to json array| JBoss.org Content Archive (Read Only)
> If i convert the datatype the ... clobs are not comparable. Generally what you would do is convert from clob to string (assuming that your json values are under 4000 characters) - cast(JSONARRAY(...) as string)...
🌐
Kodejava
kodejava.org › how-do-i-convert-csv-into-json-string-using-json-java
How do I convert CSV into JSON string using JSON-Java? - Learn Java by Examples
July 13, 2023 - package org.kodejava.json; import org.json.CDL; import org.json.JSONArray; public class CsvToJson { public static void main(String[] args) { // Comma delimited text created using text blocks String countries = """ ISO, CODE, NAME\s CZE, CZ, CZECH REPUBLIC\s DNK, DK, DENMARK\s DJI, DJ, DJIBOUTI\s DMA, DM, DOMINICA\s ECU, EC, ECUADOR """; // Convert comma delimited text into JSONArray object. JSONArray jsonCountries = CDL.toJSONArray(countries); System.out.println(jsonCountries.toString(2)); // Using a separate header and values to create JSONArray // from a comma delimited text JSONArray header
🌐
Stack Overflow
stackoverflow.com › questions › 70357603 › how-to-convert-single-string-containing-a-comma-separated-json-values-into-a-sin
java - How to convert single String containing a comma separated json values into a single json object? - Stack Overflow
... Are you sure that's the actual data? Because if it is, first strip the outer double quotes and then run through your string, counting { and }, and splitting when you see a comma while at "depth" 0.
🌐
Quora
quora.com › How-do-I-convert-string-comma-separated-values-to-JSONPath-format
How to convert string comma-separated values to JSONPath format - Quora
Answer: [code]import java.util.*; import java.util.regex.Pattern; public class Test2 { static Pattern p = Pattern.compile(","); private static final String USAGE_PT = "(@.usage"; private static final String USAGE_PT_OR = "||@.usage"; private static final String subusage_PT = "(@...
🌐
Cyber-Physical Systems
ptolemy.berkeley.edu › ptolemyII › ptII11.0 › ptII › doc › codeDoc › org › json › CDL.html
CDL
Produce a JSONArray of JSONObjects from a comma delimited text string using a supplied JSONArray as the source of element names.
Find elsewhere
🌐
Experts Exchange
experts-exchange.com › questions › 28652216 › How-to-get-convert-json-array-to-comma-separated-values.html
Solved: How to get convert json array to comma separated values | Experts Exchange
April 8, 2015 - I would like to convert the following json array to comma separated values i/p: [{"filter":"ID","filterVal ... "050882"; I tried the below code , but I am getting exception while getting filter values. Any help would be appreciated. String input ='[{"filter":"ID","filterValues":["050886","050885","050884","050883","050882"]}]'; JSONArray jsonarray = (JSONArray) new JSONTokener(input ).nextValue(); for (int i = 0; i < jsonarray.length(); i++) { JSONObject jsonobject = jsonarray.getJSONObject(i); String field= jsonobject.getString("filter"); String values= jsonobject.getString("filterValues"); }
🌐
YouTube
youtube.com › watch
Transform delimited String to JSON Array - YouTube
This video shows how we can transform the delimited string to JSON array using Custom script with the help of Org.json java library.
Published   August 3, 2024
Top answer
1 of 2
5

Just remove the internal loop

String stringFromProc = "SONY,20,30,40;LG,1,4,8";
String[] array1 =  stringFromProc.split(";"); // simply use ;
// array1[0] = SONY,20,30,40
// array1[1] = LG,1,4,8

JSONObject jsonSubObject = null;
JSONObject jsonFinal = new JSONObject();
JSONArray jsonArrayRET = new JSONArray();

for(int i=0;i<array1.length;i++){
     String []array2 = array1[i].split(","); // simply use ,
     // create jsonobjects 
     // when i=0 mean for sony and next time i = 1 mean for LG  
     jsonSubObject = new JSONObject();
     jsonSubObject.put("prodName", array2[0]);
     jsonSubObject.put("mtd", array2[1]);
     jsonSubObject.put("lmtd", array2[2]);
     jsonSubObject.put("lm", array2[3]);
     // put every object in array 
     jsonArrayRET.add(jsonSubObject);
   }
     // finally put array in reported jsonobject
     jsonFinal.put("reported", jsonArrayRET);

Note : ; and , are not special regular expressions characters so no escaping \\ is required and instead of long info just read about character class []

2 of 2
1

Move jsonFinal.put("reported", jsonArrayRET);

outside of 2nd loop, you are overwritting reported object.

    for(int i=0;i<array1.length;i++){
        String []array2 = array1[i].split("[\\,]");
        for(int j=0;j<array2.length;j++){
            System.out.println(array2[j]);
            jsonSubObject = new JSONObject();
            jsonSubObject.put("prodName", array2[0]);

            jsonSubObject.put("mtd", array2[1]);
            jsonSubObject.put("lmtd", array2[2]);
            jsonSubObject.put("lm", array2[3]);
            jsonArrayRET.add(jsonSubObject);
       }
       jsonFinal.put("reported", jsonArrayRET);
   }
🌐
Blogger
javcod1111.blogspot.com › 2011 › 06 › java-jackson-serialize-comma-separated.html
java - Jackson: Serialize comma separated string to json array -
September 22, 2017 - public class form { private string listofitems; public string getlistofitems() { return listofitems; } public void setlistofitems(string listofitems) { this.listofitems = listofitems; } @jsonproperty("listofitems") public list<integer> getarraylistofitems() { if (listofitems != null) { list<integer> items = new arraylist(); (string s : listofitems.split(",")) { items.add(integer.parseint(s)); // may throw numberformatexception } return items; } return null; } }
🌐
Microsoft Power Platform Community
powerusers.microsoft.com › t5 › Building-Flows › JSON-received-as-a-comma-separated-string-need-help-in › td-p › 676482
https://powerusers.microsoft.com/t5/Building-Flows...
Quickly search for answers, join discussions, post questions, and work smarter in your business applications by joining the Microsoft Dynamics 365 Community.
🌐
Blogger
self-learning-java-tutorial.blogspot.com › 2019 › 03 › convert-jsonarray-to-comma-separated.html
Programming for beginners: Convert JSONArray to comma separated string
March 16, 2019 - JavaScript · Julia · Kotlin · Nexus · Node.js · Prolog Tutorial · Python · R Tutorial for beginners · Spring Framework · XML · YAML · CDL.rowToString(jsonArray) method returns a comma separated string from JSONArray. JSONArray jsonArray = new JSONArray(); jsonArray.put("Chess"); ...
🌐
CopyProgramming
copyprogramming.com › howto › jackson-serialize-comma-separated-string-to-json-array
Java: Converting Comma Separated String to JSON Array in Jackson
April 4, 2023 - How to parse a JSON array of objects using Jackson?, java json spring-boot jackson jackson-databind. Share. Follow 302 2 2 silver badges 9 9 bronze badges. 2. 1. The id is a string array but you're using an Integer array – Paul Samsotha. Apr 7 at 21:07. 1. You need to change Integer[] id into String[] id into Employee class.
🌐
Stack Overflow
stackoverflow.com › questions › 55480355 › comma-separated-values-in-json-array-are-treated-as-delimiters
java - Comma Separated values in json array are treated as delimiters - Stack Overflow
April 3, 2019 - ... Please provide a minimal reproducible example. ... You should create a POJO class that is equivalent to the JSon String format. Then you can use jackson to convert the JSon string to pojo objects. It will not have the mentioned issue. Reference : https://www.mkyong.com/java/how-to-conv...