I wanted to put an array of values inside a JSONObject and it should look like this when I save it into the database:
{
"specName":"Material",
"specValue":"Fabric",
"specName":"Height",
"specValue":
['
'{
"m",
"cm",
"mm"
},
']
}';
The thing is a user would specify an attribute, say for example "Height" and its allowed types/unit of measurement for example are "meter, centimeter, and millimeter" . My current code is below:
JSONArray itemTypeArray = new JSONArray();
itemTypeArray.put(specValue);
JSONObject itemTypeObj = new JSONObject();
itemTypeObj.put("specName", specName);
itemTypeObj.put("specValue", itemTypeArray);
itemType.setItemSpecs(itemTypeObj);
But when this saves on the database, it's not as I expected and I am having a hard time looking for answers and my last resort is to ask it here. The current value that saves to the database is as follows:
{"specName":"Material,Height","specValue":["Fabric, m, cm, mm"]}
It adds everything up on the same field.
My HTML code is this:
<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>
Any help is appreciated. Thanks in advance: :)
Check out this example
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.