이 글에서는 ajax나 easyui 및 기타 프레임워크를 사용할 때 Json-lib 처리 솔루션을 주로 소개합니다. 필요한 친구들이 참고하면 됩니다.
ajax나 easyui 및 기타 프레임워크를 사용하든 백엔드에서 프런트엔드로 데이터를 출력할 때 json이 관여합니다. 이 문제를 처리하는 방법에는 두 가지가 있습니다. 첫 번째는 json을 수동으로 구성하는 것이고, 다른 하나는 json-lib를 사용하는 것입니다. 일반적인 수동 구성 방법은 매번 필드 이름에 따라 하나씩 구성해야 하므로 다른 개체에 사용할 수 없으므로 json-lib 도구를 사용하면 자동으로 달성할 수 있습니다. 처리 및 다양한 개체에 대한 다양한 처리 조치를 통해 처리 효율성과 코드 재사용성이 크게 향상되었습니다. 두 가지 방법의 프로세스는 사례를 기준으로 아래에 소개됩니다.
방법 1: 일반적인 방법, 수동 구성 변환 프로세스를 통해 easyui 요청 방법을 예로 들면, 프론트 데스크는 백그라운드에서 dategrid 요청 사용자 목록 데이터를 사용합니다. 데이터에는 공통 필드(int, String) 데이터와 날짜(date) 데이터가 있습니다.
jsp 페이지:
<table id="dg" title="用户管理" class="easyui-datagrid" fitColumns="true" pagination="true" rownumbers="true" url="${pageContext.request.contextPath}/user_list.action" fit="true" toolbar="#tb"> <thead> <tr> <th field="cb" checkbox="true" align="center"></th> <th field="id" width="50" align="center">编号</th> <th field="trueName" width="80" align="center">真实姓名</th> <th field="userName" width="80" align="center">用户名</th> <th field="password" width="80" align="center">密码</th> <th field="sex" width="50" align="center">性别</th> <th field="birthday" width="100" align="center">出生日期</th> <th field="identityId" width="130" align="center">身份证</th> <th field="email" width="120" align="center">邮件</th> <th field="mobile" width="80" align="center">联系电话</th> <th field="address" width="100" align="center">家庭地址</th> </tr> </thead> </table>
* ***************** ********************************* ****************** ******************************** ******************* ******************************* ********
액션 레이어:
public void list()throws Exception{ PageBean pageBean=new PageBean(Integer.parseInt(page), Integer.parseInt(rows)); List<User> userList=userService.findUserList(s_user, pageBean); Long total=userService.getUserCount(s_user); JSONObject result=new JSONObject(); JSONArray jsonArray=JsonUtil.formatUserListToJsonArray(userList); //easyui接收属性为rows(数据内容)和total(总记录数) result.put("rows", jsonArray); result.put("total", total); //获取response对象 ResponseUtil.write(ServletActionContext.getResponse(), result); }
******** **************************** ************************ ************************** ************************* ************************* ********************
util 도구:
public class JsonUtil { /** * 将List结果集转化为JsonArray * @param gradeService * @param stuList * @return * @throws Exception */ public static JSONArray formatUserListToJsonArray(List<User> userList)throws Exception{ JSONArray array=new JSONArray(); for(int i=0;i<userList.size();i++){ User user=userList.get(i); JSONObject jsonObject=new JSONObject(); jsonObject.put("userName", user.getUserName()); //需手动逐个配置json的key-code jsonObject.put("password", user.getPassword()); jsonObject.put("trueName", user.getTrueName()); jsonObject.put("sex", user.getSex()); jsonObject.put("birthday", DateUtil.formatDate((user.getBirthday()), "yyyy-MM-dd")); jsonObject.put("identityId", user.getIdentityId()); jsonObject.put("email", user.getEmail()); jsonObject.put("mobile", user.getMobile()); jsonObject.put("address", user.getAddress()); jsonObject.put("id", user.getId()); array.add(jsonObject); } return array; } }
방법 2: jsonLib 도구를 사용하여 처리를 완료합니다. easyui의 요청 방법을 예로 들면, 프런트엔드입니다. dategrid를 통해 백엔드에서 제품 목록 데이터를 요청합니다. 데이터에는 날짜(date) 데이터뿐만 아니라 일반 필드(int, String) 데이터도 포함됩니다. (제품 유형)
jsp 페이지:
<table id="dg" title="商品管理" class="easyui-datagrid" fitColumns="true" pagination="true" rownumbers="true" url="${pageContext.request.contextPath}/product_list.action" fit="true" toolbar="#tb"> <thead> <tr> <th field="cb" checkbox="true" align="center"></th> <th field="id" width="50" align="center" hidden="true">编号</th> <th field="proPic" width="60" align="center" formatter="formatProPic">商品图片</th> <th field="name" width="150" align="center">商品名称</th> <th field="price" width="50" align="center">价格</th> <th field="stock" width="50" align="center">库存</th> <th field="smallType.id" width="100" align="center" formatter="formatTypeId" hidden="true">所属商品类id</th> <th field="smallType.name" width="100" align="center" formatter="formatTypeName">所属商品类</th> <th field="description" width="50" align="center" hidden="true">描述</th> <th field="hotTime" width="50" align="center" hidden="true">上架时间</th> </tr> </thead> </table>
************************************ *** ************************************************ ** ************************************************* * ***********************
액션 레이어:
public void list() throws Exception{ PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows)); List<Product> productList=productService.getProducts(s_product, pageBean); long total=productService.getProductCount(s_product); //使用jsonLib工具将list转为json JsonConfig jsonConfig=new JsonConfig(); jsonConfig.setExcludes(new String[]{"orderProductList"}); //非字符串对象不予处理 jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); //处理日期 jsonConfig.registerJsonValueProcessor(ProductType.class,new ObjectJsonValueProcessor(new String[]{"id","name"}, ProductType.class)); //处理类别list对象 JSONArray rows=JSONArray.fromObject(productList, jsonConfig); JSONObject result=new JSONObject(); result.put("rows", rows); result.put("total", total); ResponseUtil.write(ServletActionContext.getResponse(), result); }
******************** ***** ********************************************* ****** ******************************************** ******* *******************************
util 도구:
/** * json-lib 日期处理类 * @author Administrator * */ public class DateJsonValueProcessor implements JsonValueProcessor{ private String format; public DateJsonValueProcessor(String format){ this.format = format; } public Object processArrayValue(Object value, JsonConfig jsonConfig) { // TODO Auto-generated method stub return null; } public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) { if(value == null) { return ""; } if(value instanceof java.sql.Timestamp) { String str = new SimpleDateFormat(format).format((java.sql.Timestamp)value); return str; } if (value instanceof java.util.Date) { String str = new SimpleDateFormat(format).format((java.util.Date) value); return str; } return value.toString(); } } /** * 解决对象级联问题 * @author Administrator * */ public class ObjectJsonValueProcessor implements JsonValueProcessor{ /** * 保留的字段 */ private String[] properties; /** * 处理类型 */ private Class<?> clazz; /** * 构造方法 * @param properties * @param clazz */ public ObjectJsonValueProcessor(String[] properties,Class<?> clazz){ this.properties = properties; this.clazz =clazz; } public Object processArrayValue(Object arg0, JsonConfig arg1) { // TODO Auto-generated method stub return null; } public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) { PropertyDescriptor pd = null; Method method = null; StringBuffer json = new StringBuffer("{"); try{ for(int i=0;i<properties.length;i++){ pd = new PropertyDescriptor(properties[i], clazz); method = pd.getReadMethod(); String v = String.valueOf(method.invoke(value)); json.append("'"+properties[i]+"':'"+v+"'"); json.append(i != properties.length-1?",":""); } json.append("}"); }catch (Exception e) { e.printStackTrace(); } return JSONObject.fromObject(json.toString()); } }
위 내용은 모두를 위해 편집했는데 앞으로도 사용하고 싶습니다. 모두에게 도움이 됩니다.
관련 기사:
위 내용은 Ajax 또는 Easyui와 같은 프레임워크를 사용할 때 Json-lib 처리 솔루션(그래픽 튜토리얼)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Python 및 JavaScript의 미래 추세에는 다음이 포함됩니다. 1. Python은 과학 컴퓨팅 분야에서의 위치를 통합하고 AI, 2. JavaScript는 웹 기술의 개발을 촉진하고, 3. 교차 플랫폼 개발이 핫한 주제가되고 4. 성능 최적화가 중점을 둘 것입니다. 둘 다 해당 분야에서 응용 프로그램 시나리오를 계속 확장하고 성능이 더 많은 혁신을 일으킬 것입니다.

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.

예, JavaScript의 엔진 코어는 C로 작성되었습니다. 1) C 언어는 효율적인 성능과 기본 제어를 제공하며, 이는 JavaScript 엔진 개발에 적합합니다. 2) V8 엔진을 예를 들어, 핵심은 C로 작성되며 C의 효율성 및 객체 지향적 특성을 결합하여 C로 작성됩니다.

JavaScript는 웹 페이지의 상호 작용과 역학을 향상시키기 때문에 현대 웹 사이트의 핵심입니다. 1) 페이지를 새로 고치지 않고 콘텐츠를 변경할 수 있습니다. 2) Domapi를 통해 웹 페이지 조작, 3) 애니메이션 및 드래그 앤 드롭과 같은 복잡한 대화식 효과를 지원합니다. 4) 성능 및 모범 사례를 최적화하여 사용자 경험을 향상시킵니다.

C 및 JavaScript는 WebAssembly를 통한 상호 운용성을 달성합니다. 1) C 코드는 WebAssembly 모듈로 컴파일되어 컴퓨팅 전력을 향상시키기 위해 JavaScript 환경에 도입됩니다. 2) 게임 개발에서 C는 물리 엔진 및 그래픽 렌더링을 처리하며 JavaScript는 게임 로직 및 사용자 인터페이스를 담당합니다.

JavaScript는 웹 사이트, 모바일 응용 프로그램, 데스크탑 응용 프로그램 및 서버 측 프로그래밍에서 널리 사용됩니다. 1) 웹 사이트 개발에서 JavaScript는 HTML 및 CSS와 함께 DOM을 운영하여 동적 효과를 달성하고 jQuery 및 React와 같은 프레임 워크를 지원합니다. 2) 반응 및 이온 성을 통해 JavaScript는 크로스 플랫폼 모바일 애플리케이션을 개발하는 데 사용됩니다. 3) 전자 프레임 워크를 사용하면 JavaScript가 데스크탑 애플리케이션을 구축 할 수 있습니다. 4) node.js는 JavaScript가 서버 측에서 실행되도록하고 동시 요청이 높은 높은 요청을 지원합니다.

Python은 데이터 과학 및 자동화에 더 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 더 적합합니다. 1. Python은 데이터 처리 및 모델링을 위해 Numpy 및 Pandas와 같은 라이브러리를 사용하여 데이터 과학 및 기계 학습에서 잘 수행됩니다. 2. 파이썬은 간결하고 자동화 및 스크립팅이 효율적입니다. 3. JavaScript는 프론트 엔드 개발에 없어서는 안될 것이며 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축하는 데 사용됩니다. 4. JavaScript는 Node.js를 통해 백엔드 개발에 역할을하며 전체 스택 개발을 지원합니다.

C와 C는 주로 통역사와 JIT 컴파일러를 구현하는 데 사용되는 JavaScript 엔진에서 중요한 역할을합니다. 1) C는 JavaScript 소스 코드를 구문 분석하고 추상 구문 트리를 생성하는 데 사용됩니다. 2) C는 바이트 코드 생성 및 실행을 담당합니다. 3) C는 JIT 컴파일러를 구현하고 런타임에 핫스팟 코드를 최적화하고 컴파일하며 JavaScript의 실행 효율을 크게 향상시킵니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

드림위버 CS6
시각적 웹 개발 도구

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

Dreamweaver Mac版
시각적 웹 개발 도구

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!
