简体   繁体   English

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

[英]How do I put 2 or more values in a JSONArray that is inside a JSONObject in Spring Boot?

I wanted to put an array of values inside a JSONObject and it should look like this when I save it into the database:我想将一组值放入 JSONObject 中,当我将其保存到数据库中时它应该如下所示:

{
"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:我的 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>

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);
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM