简体   繁体   English

在java中的Json String中用双引号包裹键值对

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

To make it into a valid JSON使其成为有效的 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":""}]}

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.要将上述对象转换为 JSON,您需要将键和值作为字符串,如下所示,稍后您可以解析 JSON 以评估条件语句。

{
"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
    }
]}

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.尽管此代码给出了您想要的结果,但您可以找到更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM