[英]How do I put 2 or more values in a JSONArray that is inside a JSONObject in Spring Boot?
我想将一组值放入 JSONObject 中,当我将其保存到数据库中时它应该如下所示:
{
"specName":"Material",
"specValue":"Fabric",
"specName":"Height",
"specValue":
['
'{
"m",
"cm",
"mm"
},
']
}';
问题是用户会指定一个属性,例如“高度” ,其允许的类型/测量单位例如是“米、厘米和毫米” 。 我当前的代码如下:
JSONArray itemTypeArray = new JSONArray();
itemTypeArray.put(specValue);
JSONObject itemTypeObj = new JSONObject();
itemTypeObj.put("specName", specName);
itemTypeObj.put("specValue", itemTypeArray);
itemType.setItemSpecs(itemTypeObj);
但是当这保存在数据库中时,它并不像我预期的那样,我很难寻找答案,我最后的手段是在这里问它。 保存到数据库的当前值如下:
{"specName":"Material,Height","specValue":["Fabric, m, cm, mm"]}
它将所有内容添加到同一个字段中。
我的 HTML 代码是这样的:
<div>
<label>Type: </label>
<input type="text" th:field="*{typeName}" />
</div>
<div>
<div class="specFields-wrapper">
</div>
<button type="button" class="c-button submit" onclick="addSpec();">Add Specification</button>
</div>
<script text="text/javascript">
function addSpec() {
let specFieldLabel = '<span>Label: <input type="text" name="specName"></span>\r\n';
let specFieldValue = '<span>Value: <input type="text" name="specValue"></span>\r\n';
document.querySelector('.specFields-wrapper').innerHTML += (specFieldLabel+specFieldValue)+'<br>';
}
</script>
任何帮助表示赞赏。 提前致谢: :)
看看这个例子
public static void main(String[] args) throws Exception {
JSONObject json1 = new JSONObject();
json1.put("specName", "Material");
json1.put("specValue", "Fabric");
JSONObject json2 = new JSONObject();
json2.put("specName", "Height");
json2.put("specValue", new JSONArray(Arrays.asList("m","cm","mm")));
JSONArray array = new JSONArray();
array.put(json1.toMap());
array.put(json2.toMap());
String jsonFormatted = array.toString(2);
System.out.println(jsonFormatted);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.