Masterbuilder
Masterbuilder

Reputation: 509

convert a comma separated string to json in java

I have a comma separated string which needs to converted into a JSON string, When I make the JSONArray conversion it is still in array format. What is the best way to solve this.

String str="art,0.0, comedy,0.0, action,0.0, crime,0.0, animals,0.0"

expected output

{"art":"0.0", "comedy":"0.0","action":"0.0","crime":"0.0","animals":"0.0"}

Here is the code I tried

String [] arrayStr=strVal.split(",");
JSONArray mJSONArray = new JSONArray();
for (String s: arrayStr){
    mJSONArray.put(s);
}
System.out.println(mJSONArray.toString());

output

["art","0.0"," comedy","0.0"," action","0.0"," crime","0.0"," animals","0.0"]

Upvotes: 2

Views: 12335

Answers (3)

ccjmne
ccjmne

Reputation: 9628

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.

Upvotes: 4

Slava Vedenin
Slava Vedenin

Reputation: 60164

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)

Upvotes: 2

jt-gilkeson
jt-gilkeson

Reputation: 2721

It looks like you want to use JSONObject not JSONArray to get the desired output. i.e. just add the items to the object - jsonObject.put(key, value)

Upvotes: 0

Related Questions