0
json을 처음 사용합니다. 서블릿에서 json을 만들 수 있습니다. 하지만서블릿에서 사용자 정의 json을 작성하십시오.
{
"name":"Employee",
"children":[{
"name":"Subho"
},
{
"name":"jeet",
"children":[{
"name":"rahul"
},
{
"name":"abhijit"
}]
}]
}
는하지만 내가 만드는 것은
이{
"children":[
{"name":"Culture"},
{"name":"Salary"},
{"name":"Work"},
{"name":"Economy"}
],
"name":"Employee"
}
내 서블릿 코드 - 이것도 '예요 below- 같은 JSON을 만들
public class ActionServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Random r = new Random();
int low = 0;
int high = 5;
int R = r.nextInt(high - low) + low;
/*Sample data for child nodes actual data will be called here*/
String arr[] = {"Culture", "Salary", "Work", "Economy"};
/*Responsible for creation of the child nodes and their names */
Map<String, String> mapping = new HashMap<String, String>();
EntryListContainer entryListContainer = new EntryListContainer();
List<Entry> entryList1 = new ArrayList<Entry>();
for (int i = 0; i < R; i++) {
/*Model object for the Link*/
Entry entry1 = new Entry();
entry1.setChildren(arr[i]);
entryList1.add(entry1);
}
entryListContainer.setEntryList1(entryList1);
/*Root node this will collapse and get back to Original position on click*/
entryListContainer.setName("Employee");
mapping.put("entryList1","name");
Gson gson = new GsonBuilder().serializeNulls().setFieldNamingStrategy(new DynamicFieldNamingStrategy(mapping)).create();
System.out.println(gson.toJson(entryListContainer));
String json = null;
/*conversion of the json from the generated java object*/
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
json = new Gson().toJson(gson);
System.out.println(json);
response.getWriter().write(gson.toJson(entryListContainer));
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
이것은 EntryListContainer 클래스
되는 경계하고public class EntryListContainer {
private List<Entry> children;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setEntryList1(List<Entry> entryList1) {
this.children = entryList1;
}
public List<Entry> getEntryList1() {
return children;
}
DynamicFieldNamingStrategy 클래스
public class DynamicFieldNamingStrategy implements FieldNamingStrategy{
private Map<String, String> mapping;
public DynamicFieldNamingStrategy(Map<String, String> mapping) {
this.mapping = mapping;
}
@Override
public String translateName(Field field) {
String newName = mapping.get(field.getName());
if (newName != null) {
return newName;
}
return field.getName();
}
이 서블릿 코드는 json을 작성 중입니다. 여기서는 모든 자식 노드를 만들고 목록 (여기서는 entryList1)에 넣은 다음 해시 맵에 배치합니다. 하지만 제가 만든 것은 내 요구 사항을 충족하지 않습니다 ..
는 에게사람이 나를 도와주세요 ..