1

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 Answers1

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;
Ankit
  • 257
  • 1
  • 3
  • 13
  • What is obj.getNo? How can I pass data from html input field here! –  Mar 23 '16 at 13:03
  • Edited my reply for basic understanding – Ankit Mar 23 '16 at 13:11
  • I need link to Jackson Json Library –  Mar 23 '16 at 13:26
  • http://search.maven.org/#artifactdetails|com.fasterxml.jackson.datatype|jackson-datatype-json-org|2.7.3|bundle – Ankit Mar 23 '16 at 13:37
  • I m having some trouble in adding the content to file, I am using Filewriter class, How to save changes to file? –  Mar 23 '16 at 14:13
  • You can convert the json to string. just do root.toString() and follow this post for writing to file http://stackoverflow.com/questions/2885173/how-to-create-a-file-and-write-to-a-file-in-java – Ankit Mar 23 '16 at 14:53