[英]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.