How to add data to json using java?

﹥>﹥吖頭↗ 提交于 2021-01-28 22:08:53

问题


I have html form with two input field, which I am adding to json file on button click!

JSON File

{
  "data": 
    {
      "names": [
        {
          "no": 1,
          "name": "John"
        },
        {
          "no": 2,
          "name": "Paul"
        }
        ]
     }
}

Java File

String vNo = "";
String vNAme = "";


JSONParser parser = new JSONParser();



if(request.getParameter("save")!=null) 
{
   vNo = request.getParameter("no_form");
   vName = request.getParameter("name_form");


   JSONObject element = new JSONObject();
   element.put("no", vNo);
   element.put("name", vName);

   JSONArray names = new JSONArray();

   names.add();

 }

I m using JSON simple, I m getting confused How can I add data from input field to JSON array "names"?

JSON File after adding content must look like this

{
  "data": 
    {
      "names": [
        {
          "no": 1,
          "name": "John"
        },
        {
          "no": 2,
          "name": "Paul"
        },
        {
          "no": 3,
          "name": "Jake"
        }
        ]
     }
}

回答1:


I use the Jackson Json library to do this.

using that library you can do this

     vNo1 = request.getParameter("no1_form");
     vName1 = request.getParameter("name1_form");


     vNo = request.getParameter("no_form");
     vName = request.getParameter("name_form");


    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.createObjectNode();
    ArrayNode names = mapper.createArrayNode();

       ObjectNode item1 = mapper.createObjectNode();
       item1.put("no", vNo1);
       item1.put("name", vName1); 
       names.add(item1);

       ObjectNode item2 = mapper.createObjectNode();
       item2.put("no", vNo);
       item2.put("name", vName); 
       names.add(item2);

    root.put("names", names);

   return root;



回答2:


See below code:

JSONObject mainNode = new JSONObject();
Collection<JSONObject> items = new ArrayList<JSONObject>();

/*************1st element**************/
JSONObject element = new JSONObject();
element.put("no", vNo);
names.put("name", vName);
items.add(element);

/*************2st element**************/
JSONObject element1 = new JSONObject();
element1.put("no", vNo1);
element1.put("name", vName1);
items.add(element1);

/*************Add into root element**************/
mainNode.put("data", new JSONArray(items));


来源:https://stackoverflow.com/questions/36178378/how-to-add-data-to-json-using-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!