skip to Main Content

How to convert following string to json or object in java 17

{name=sachin, style=short, country=india}

2

Answers


  1. To convert to json, replace all word boundaries with a quote:

    String json = str.replaceAll("\b", """);
    

    To convert that to an Object, deserialise using your favourite library (eg using ObjectMapper)

    Login or Signup to reply.
  2. You can convert String to JSON with the help of JsonParser, here’s the following code

    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    
    public class StringToJsonConverter {
        public static void main(String[] args) {
            String inputString = "{name=sachin, style=short, country=india}";
            JsonObject jsonObject = parseStringToJsonObject(inputString);
            System.out.println(jsonObject.toString());
        }
    
        public static JsonObject parseStringToJsonObject(String inputString) {
            JsonParser jsonParser = new JsonParser();
            JsonObject jsonObject = (JsonObject) jsonParser.parse(inputString.replaceAll("=", ":"));
            return jsonObject;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search