如何在 Spring Boot 中的 JSONObject 中的 JSONArray 中放置 2 个或更多值?



我想在 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>rn';
let specFieldValue = '<span>Value: <input type="text" name="specValue"></span>rn';
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);
}

最新更新