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

Posted

技术标签:

【中文标题】如何在 Spring Boot 中的 JSONObject 内的 JSONArray 中放置 2 个或更多值?【英文标题】:How do I put 2 or more values in a JSONArray that is inside a JSONObject in Spring Boot? 【发布时间】:2020-09-14 11:02:06 【问题描述】:

我想在 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>

感谢任何帮助。提前致谢! :)

【问题讨论】:

您在 json 节点中指定了一个名为 specValue 的重复键。当地图第二次尝试放置它时,它只会更新第一个条目。一些 javadoc:如果映射先前包含键的映射,则旧值将替换为指定值。 你的 JSON 应该像:["specName":"Material", "specValue":"Fabric", "specName":"Height", "specValue":["m", "cm", "mm"]]? @AlexRudenko 是的,它应该是这样的 @Kostakiiiis 我认为这是因为我编写的 html 仅添加了一个新字段,该字段与第一次单击按钮时添加的第一个字段完全相同。我不确定该怎么做... 【参考方案1】:

看看这个例子

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

【讨论】:

我看到这个例子的结果是我需要的输出,但我认为问题真的来自 HTML 和 JavaScript 的行为方式,我还没有弄清楚。不过谢谢你。

以上是关于如何在 Spring Boot 中的 JSONObject 内的 JSONArray 中放置 2 个或更多值?的主要内容,如果未能解决你的问题,请参考以下文章