Puedes usar abajo como.
Si quieres usar json array:
- descargar json-simple-1.1.1.jar y agréguelo a su ruta de clase de proyecto
Crear una clase llamada Modelo como abajo
public class Model {
private String id = "";
private String name = "";
//getter sertter here
}
En sevlet getMethod puedes usar como abajo
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//begin get data from databse or other source
List<Model> list = new ArrayList<>();
Model model = new Model();
model.setId("101");
model.setName("Enamul Haque");
list.add(model);
Model model1 = new Model();
model1.setId("102");
model1.setName("Md Mohsin");
list.add(model1);
//End get data from databse or other source
try {
JSONArray ja = new JSONArray();
for (Model m : list) {
JSONObject jSONObject = new JSONObject();
jSONObject.put("id", m.getId());
jSONObject.put("name", m.getName());
ja.add(jSONObject);
}
System.out.println(" json ja = " + ja);
response.addHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(ja.toString());
response.getWriter().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
Salida :
[{"name":"Enamul Haque","id":"101"},{"name":"Md Mohsin","id":"102"}]
Quiero json Object solo use como:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
JSONObject json = new JSONObject();
json.put("id", "108");
json.put("name", "Enamul Haque");
System.out.println(" json JSONObject= " + json);
response.addHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(json.toString());
response.getWriter().flush();
// System.out.println("Response Completed... ");
} catch (Exception e) {
e.printStackTrace();
}
}
Función anterior Salida :
{"name":"Enamul Haque","id":"108"}
La fuente completa se proporciona a GitHub: https://github.com/enamul95/ServeletJson.git
{ key1: value1, key2: value2 }
?