Reputation:
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"
}
]
}
}
Upvotes: 1
Views: 6362
Reputation: 267
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;
Upvotes: 1