要使用变量作为 JSON 值或在方法内创建 JSON 对象,可以使用不同编程语言的相应特性。
var myVariable = "hello";
var myJson = {
key: myVariable
};
console.log(myJson); // 输出: { "key": "hello" }
import json
myVariable = "hello"
myJson = {
"key": myVariable
}
jsonString = json.dumps(myJson)
print(jsonString) # 输出: {"key": "hello"}
使用 Jackson 库的示例:
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
String myVariable = "hello";
String jsonString = "{\"key\":\"" + myVariable + "\"}";
try {
MyJsonClass myJson = objectMapper.readValue(jsonString, MyJsonClass.class);
System.out.println(myJson.getKey()); // 输出: hello
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MyJsonClass {
private String key;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
使用 Gson 库的示例:
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
String myVariable = "hello";
MyJsonClass myJson = new MyJsonClass();
myJson.setKey(myVariable);
String jsonString = gson.toJson(myJson);
System.out.println(jsonString); // 输出: {"key":"hello"}
}
}
class MyJsonClass {
private String key;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
以上是一些常见编程语言的示例,具体的实现方法可能因编程语言和库的不同而有所差异。