-2

I would like to convert this, which I don't know what it's called, to Json. Can you help me?

[{key1=value1,key2=value2,key3=value3}]

The result has to be this: { "key1":"value1", "key2":"value2", "key3":"value3" }

Geras
  • 21
  • 4

1 Answers1

1

Assuming this is the contents of a Map object, you can use Gson to convert between Java objects (including custom objects) into JSON, and JSON back into an object. That would look like this:

Gson gson = new Gson();
String json = gson.toJson(YOUR_MAP);

Going back to a map:

Gson gson = new Gson();
Type type = new TypeToken<Map<KEY_TYPE, VALUE_TYPE>>(){}.getType();
Map YOUR_MAP = gson.fromJson(JSON, type);

And if this is not a Map and just a strange string that wants to be a Map but couldn't quite make it you can just format the string by:

  1. Removing both sets of brackets at the ends using the substring(int start, int end) method
  2. Separate the entries by the commas and equals by using split(",|=")
  3. Reassembling the String with the quotes as JSON

    • String JSON = "{ \"" + arrayFromOriginalString[1] + "\":\"", arrayFromOriginalString[2]... assuming the source string always has the same amount of entries
    • If the source is always different you can use a for loop and increment by 2

      String json = "{";
      
      for(int i = 0; i < YOUR_ARRAY.length; i += 2;) {
          json += "\"" + YOUR_ARRAY[i] + "\":\"" + YOUR_ARRAY[i + 1] + "\"";
      
          //Some kind of if condition to decide if a comma is required (Last entry)
      }
      
      json += "}";
      

Here is a fully functioning example of this code

Weirdest
  • 67
  • 1
  • 1
  • 8