vinay saddanapu
vinay saddanapu

Reputation: 31

Wrap the key-value pairs with double quotes in Json String in java

To make it into a valid JSON

"{containerId:81,params:[{parameterName:vinay,valueInDesignMode:where actor_id<50,valueInRunMode:where actor_id<100},{parameterName:name,valueInDesignMode:where actor < =10,valueInRunMode:},{parameterName:nameID,valueInDesignMode:,valueInRunMode:}]}"

Expected output

{"containerId":81,"params":[{"parameterName":"vinay","valueInDesignMode":"where actor_id<50","valueInRunMode":"where actor_id<100","containerId":81},{"parameterName":"name","valueInDesignMode":"where actor < =10","valueInRunMode":""},{"parameterName":"nameID","valueInDesignMode":"","valueInRunMode":""}]}

Upvotes: 0

Views: 898

Answers (2)

Eskandar Abedini
Eskandar Abedini

Reputation: 2144

Please check this:

public static void main(String[] args) {
    String inputJson = "{containerId:81,params:[{parameterName:vinay,valueInDesignMode:where actor_id<50,valueInRunMode:where actor_id<100},{parameterName:name,valueInDesignMode:where actor < =10,valueInRunMode:},{parameterName:nameID,valueInDesignMode:,valueInRunMode:}]}";

    String outputJson =
            inputJson
                    .replace(" ", "")
                    .replaceAll("([\\w]+):", "\"$1\":")
                    .replaceAll(":([\\w|<|=]+)", ": \"$1\"")
                    .replaceAll("\"([\\d]+)\"", "$1")
                    .replace(":}", ": \"\"}")
                    .replace(":]", ": \"\"]")
                    .replace(":,", ": \"\",");        

    System.out.println(outputJson);
}

Although this code gives your desired result but you can find better solutions.

Upvotes: 1

sakshi malik
sakshi malik

Reputation: 100

To convert the above Object to JSON you need to make the key and value as a string like the below and later you can parse the JSON to evaluate the conditional statements.

{
"containerId":81,
"params":[
    {
        "parameterName":"vinay",
        "valueInDesignMode":"where actor_id<50",
        "valueInRunMode":"where actor_id<100"
    },
    {
        "parameterName":"name",
        "valueInDesignMode":"where actor < =10",
        "valueInRunMode":null
    },
    {
        "parameterName":"nameID",
        "valueInDesignMode": null,
        "valueInRunMode":null
    }
]}

Upvotes: 0

Related Questions