将字符串变量插入到字符串形式的JSON中



我有一个JSON有效负载保存为字符串

String jsonBody = “{n”
+ ” “example“: {n”
+ ”  “example“: [n”
+ ”   {n”
+ ”    “example“: 100,n”
+ ”    “this_is_example_json_key“: “this_is_example_json_value“,n”

我通过将body从i.e. Postman复制到

来创建它String jsonBody = "here I pasted the body";

不幸的是,我不能在那里硬编码所有内容,所以我必须将一些值更改为变量。邮差中的JSON看起来像:

"this_is_example_json_key":"x"

以此类推。让我们假设:

String x = “this_is_example_json_value“;

如果我把它替换成

+ ” “this_is_example_json_key“: “ + x + “,n”

之类的,body中的值就是this_is_example_json_value,其中我需要"this_is_example_json_value">(";"标记是值的一部分)。

问题是,如何设置这些+/"在字符串中,所以最后在JSON的值中,我将得到&quot中的值;"。

我试着玩"/+但这些都不工作。变量必须带有";否则,API将返回一个错误。

从java 15开始,如果你只想使用字符串,你也可以这样做:

int this_is_example_json_value= 100;
String json = """
{
"this_is_example_json_key":  %d
}
""".formatted(this_is_example_json_value);

这里是官方的jep。

不要尝试使用字符串构建JSON。使用合适的JSON解析器

import org.json.JSONException;
import org.json.JSONObject;
public class Eg {
public static void main(String[] args) throws JSONException {
String x = "this_is_example_json_value";
JSONObject example = new JSONObject();
example.put("this_is_example_json_key", x);
System.out.println(example.toString());
}
}

输出:

{"this_is_example_json_key":"this_is_example_json_value"}

不用担心需要转义什么。

你可以使用额外的"";">

String x = "this_is_example_json_value";
String jsonBody = "{n"
+ ""example": {n"
+ "  "example": [n"
+ "  {n"
+ " "example": 100,n"
+ ""this_is_example_json_key":" + """ + x + """ + "n }"
+"n  ]n   }n    }";

在这里你会得到一个json字符串

{
"example": {
"example": [
{
"example": 100,
"this_is_example_json_key": "this_is_example_json_value"
}
]
}
}

最新更新