我有一个像这样的json字符串
{
"bitrate": false,
"bitrateInit": 40000,
"bitr": 10000
}
我必须在此后面添加以下数据
"test": {"enable":true }
最终数据将是
{
"bitrate": false,
"bitrateInit": 40000,
"bitr": 10000,
"test": {"enable":true }
}
我如何用Java执行它
String str= "{"bitrate":false,"bitrateInit":40000,"bitr":10000}";
JSONObject jObj = new JSONObject(str);
如何将这个'str'值附加到现有的josn对象中
答案 0 :(得分:3)
尝试一下:
String str= "{\"bitrate\":false,\"bitrateInit\":40000,\"bitr\":10000}";
String str2= "{\"enable\":true }";
JSONObject jObj = new JSONObject(str);
jObj.put("test", new JSONObject(str2));
System.out.println(jObj);
答案 1 :(得分:2)
解析您的json字符串,然后将其首先转换为JSONobject。
JSONObject jsonObj = new JSONObject(str);
现在使用test
创建put()
json对象并将其放入其中。
JSONObject test = new JSONObject();
test.put("enable", true);
jsonObj.put("test", test);
答案 2 :(得分:1)
创建两个模型类,然后将其放在地图上。示例如下:
Model1.java
import java.io.Serializable;
public class Model1 implements Serializable {
private static final long serialVersionUID = 1L;
private boolean bitrate;
private int bitrateInit;
private int bitr;
private Test test;
public boolean isBitrate() {
return bitrate;
}
public void setBitrate(boolean bitrate) {
this.bitrate = bitrate;
}
public int getBitrateInit() {
return bitrateInit;
}
public void setBitrateInit(int bitrateInit) {
this.bitrateInit = bitrateInit;
}
public int getBitr() {
return bitr;
}
public void setBitr(int bitr) {
this.bitr = bitr;
}
public Test getTest() {
return test;
}
public void setTest(Test test) {
this.test = test;
}
}
Test.java
import java.io.Serializable;
public class Test implements Serializable {
private static final long serialVersionUID = 1L;
private boolean enable;
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
}
RequestController.java
@RestController
public class RequestController {
@RequestMapping(value = BASE_URL + "getAllData", method = RequestMethod.GET)
@ResponseBody
public HashMap<String, Object> getAllData () {
HashMap<String, Object> plr = new HashMap<String, Object>();
Test t = new Test();
t.setEnable(true);
Model1 model1 = new Model1();
model1.setBitrate(true);
model1.setBitrateInit(180000);
model1.setBitr(1400);
model1.setTest(t);
plr.put("data", model1);
return plr;
}
}
输出:
{
"data": {
"bitrate": true,
"bitrateInit": 180000,
"bitr": 1400,
"test": {
"enable": true
}
}
}
答案 3 :(得分:-2)
obj = {
"bitr": 10000,
"bitrate": false,
"bitrateInit": 40000
};
var newVar = "test";
var newVal = {"enable":true };
obj[newVar] = newVal;
console.log(obj);
//Result will be
{
"bitr": 10000,
"bitrate": false,
"bitrateInit": 40000,
"test": {"enable":true }
}