Körük gibi kullanabilirsiniz.
Json dizisini kullanmak istiyorsanız:
- indir json-simple-1.1.1.jar & proje sınıfı yoluna ekle
Feryat gibi Model adında bir sınıf oluşturun
public class Model {
private String id = "";
private String name = "";
//getter sertter here
}
Sevlet getMethod'da feryat gibi kullanabilirsiniz
@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();
}
}
Çıktı :
[{"name":"Enamul Haque","id":"101"},{"name":"Md Mohsin","id":"102"}]
Json Object sadece gibi kullanmak istiyorum:
@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();
}
}
Yukarıdaki fonksiyonu Çıkışı :
{"name":"Enamul Haque","id":"108"}
GitHub'a tam kaynak verilir: https://github.com/enamul95/ServeletJson.git
{ key1: value1, key2: value2 }
?