기초 매트리스
Java에는 Jackjson, Fastjson, GSON 등과 같은 JSON에 대한 많은 Lib가 있습니다. 그러나 나는 그것들을 사용했지만 Java 객체를 JSON 문자열로 반환 할 필요가있는 프로그래머에게는 여전히 너무 무겁게 보입니다. 또한 일부 기능은 매우 사용자 정의 할 수 있습니다. 예를 들어, Java 객체의 속성이 비어 있으면 이러한 구성 요소가 출력되지 않습니다. 따라서 페이지의 목록 개체를 통과 할 때이 속성이 정의되지 않은지 판단해야하므로 매우 불만족합니다. 그래서 나는 무슨 일이 일어나고 있는지 연구하기 위해 시간이 걸리기로 결정했습니다.
그러나 아침을 면밀히 살펴본 후, 나는 Fastjson과 Gson이 매우 복잡한 방식으로 작성되었으며 관련 문서 나 의견이 없었기 때문에 마침내 포기했습니다. 그래서 www.json.com에서 JSON을 반환하는 비교적 간단한 Java 패키지를 발견했습니다. 이 lib는 5 개의 Java 클래스 만 있으면됩니다. 이것이 바로 제가 원하는 것입니다. 공식 Jsonarray는 Javabeans의 직접 전환을 지원하지 않습니다. 예를 들어 List <user>와 같은 것들을 변환 할 수 없습니다. 변환하려면 List <map>과 같은 형식으로 변환해야하므로 수정해야합니다. 공식 문서에는 다음이 포함됩니다.
먼저 기본 사용법을 소개하겠습니다.
JsonObject 클래스를 사용하여 기본 Java 객체를 처리하면 사용법은 다음과 같습니다.
public void testmap () {map <string, object> map = new Hashmap <string, object> (); map.put ( "이름", "qiu"); map.put ( "비밀번호", "123"); map.put ( "주소", "중국"); 사용자 user = 새 사용자 (); user.setusername ( "qiuqiu"); user.setpassword ( "123456"); user.gettels (). add ( "12344445556677"); user.getTels (). add ( "6893493458585"); map.put ( "사용자", 사용자); jsonobject json = 새로운 jsonobject (map); System.out.println (json.toString ()); } 수집 객체 인 경우 JSONARRAY 클래스가 사용되며 사용법은 다음과 같습니다.
public void testList ()는 jsOnexception {list <user> list = new ArrayList <user> (); 사용자 user = 새 사용자 (); user.setusername ( "qiuqiu"); user.setpassword ( "123456"); user.gettels (). add ( "12344445556677"); user.getTels (). add ( "6893493458585"); user user2 = 새 사용자 (); user2.setusername ( "중국"); user2.gettels (). add ( "123444445556677"); user2.gettels (). add ( "6893493458585"); list.add (사용자); list.add (user2); JSONARRAY JSON = NEW JSONARRAY (List); System.out.println (json.tostring (2)); } 위의 코드 에서이 LIB의 사용이 매우 간단하다는 것을 알 수 있습니다. GSON과 같은 새로운 객체가 필요하지 않으며 FastJson의 API 디자인도 다소 비합리적입니다. 위의 두 번째 코드에는 새 라인에서 두 개의 공간을 들여 쓰기함으로써 출력을 나타내는 토스트 링 (2)이 있습니다.
위는 기본 사용 만 소개하지만 이것은 원하는 것이 아닙니다. 당신이 원하는 것은 객체 속성이 비어있을 때 아무것도 반환하지 않고 빈 문자열을 반환하는 방법입니다. 5 개의 수업이 있지만 장소를 찾는 데 2 ~ 3 시간이 걸렸습니다. jsonobject에는 populatemap이라는 방법이 있으며, 결국에는 작은 코드가 있습니다.
Object result = method.invoke (bean, (Object []) null); if (result! = null) {this.map.put (키, 랩 (결과)); }즉, get 메소드가 호출되고 Null로 반환되면이 속성은 출력되지 않습니다. 물론 변경하는 것은 매우 간단합니다.
Object result = method.invoke (bean, (Object []) null); this.map.put (key, result == null? "": 랩 (결과);
이것은 마침내 내가 해결하고 싶었던 문제를 해결했습니다. 물론,이 lib는 공식적으로 JSON에 의해 가져오고 매우 간단하게 작성되었습니다. Pagination 디스플레이와 같이 한 번에 몇 가지 또는 수십 개의 데이터 만있는 상황에 더 적합합니다. 한 번에 전송 된 데이터의 양이 상대적으로 크면 Fastjson 등을 사용하는 것을 고려할 수 있지만 개인적으로 대부분의 경우 가장 필요한 사용자 정의가 있다고 생각합니다. 예를 들어, 때때로 요구를 충족시킬 수없는 특정 구성 요소를 찾으면 구성 요소에는 문서 나 주석이 없으며 코드를 이해하기 어렵습니다. 이는 기본적으로 오픈 소스가 아닌 것과 동일하므로 의미가 없습니다.
예제 요약
import java.io.ioexception; import java.io.printwriter; import javax.servlet.http.httpservletresponse; com.alibaba.fastjson.json import; com.alibaba.fastjson.serializer.serializerfeature import; / **** 웹 서버는 JSON 도구 클래스를 반환* 도구 클래스* FASTJSON* 도구 클래스를 지원합니다. / *** JSONP 기본 콜백 함수*/ 개인 정적 문자열 콜백 = "콜백"; /*** FASTJSON SERIALIZATE SETTERS*/PRIVATE STATIC SERIALIZERFEATURE [] FEACTIONS = NEW SERIALIZERFEATURE [] {// 맵에서 NULL의 값을 출력하여 SerializerFeature.WriteMapnullValue, // 부울 객체가 NULL이면 Fally SerializerFeature.WritEnullBooleanfalse, // if is alull is null입니다. serializerfeature.writenullListasEmpty, // 숫자가 null 인 경우 출력은 0 SerializerFeature.WritenUllNumberAszero, // 출력 NULL String SerializerFeature.WritenUllStringAsempty, // 출력 날짜 SerializerFeature.WritedAdeAdateFormat}; / *** JSON Serialization* @return JSON String*/ private static string tojsonstring (Object obj) {return json.tojsonstring (obj, feature); }/*** return JSON 형식 데이터* @Param Response* @param 데이터 java 객체를 반환합니다* @param 인코딩 JSON 문자열의 인코딩 형식*/public static void json (httpservletResponse 응답, 객체 데이터, 문자열 encoding) {// accoding responshipe ( "텍스트/평범한); 응답 .SetchAracterEncoding (인코딩); printwriter out = null; try {out = response.getwriter (); out.write (tojsonstring (data)); out.flush (); } catch (ioexception e) {e.printstacktrace (); }} / *** 기본 인코딩을 사용하여 JSON 형식 데이터를 반환합니다.* @param Data Java 개체를 반환 할* / public static void json (httpservletResponse 응답, 개체 데이터) {json (응답, 데이터, 인코딩); } / *** 기본 인코딩 및 기본 콜백 함수를 사용하여 JSONP 데이터를 반환합니다.* @Param Data* @Param Data JSONP DATA* / public static void jsonp (httpservletResponse 응답, 객체 데이터) {JSONP (응답, 콜백, 데이터, 송금); } / *** 기본 인코딩* @param 콜백 콜백 함수 이름* @param data jsonp data* / public static void jsonp (httpservletresponse 응답, 문자열 콜백, 객체 데이터) {jsonp (응답, 콜백, 데이터, 인코딩); } / *** return jsonp data* @param response* @param 콜백 JSONP 콜백 함수 이름* @param data jsonp data* @param jsonp data* / public static void jsonp (httpservletresponse 응답, 문자열 콜백, 객체 데이터, 문자열 인코딩) {stringbuffer sb = new stringbuffer (콜백); sb.append ( "("); sb.append (tojsonstring (data)); sb.append ( ");"); // 인코딩 형식을 설정합니다. 응답 .SetchAracterEncoding (인코딩); printwriter out = null; try {out = response.getwriter (); out.write (sb.tostring ()); out.flush (); } catch (ioexception e) {e.printstacktrace (); }} public static string getencoding () {return encoding; } public static void setencoding (String encoding) {responsejsonutils.encoding = 인코딩; } public static String getCallback () {return 콜백; } public static void setCallback (문자열 콜백) {responsejsonutils.callback = 콜백; }} /*** Servlet에서 JSON 데이터를 반환*/@webservlet ( "/json.do") public class jsonservlet는 httpservlet를 확장합니다. / *** 반환 json 형식 데이터*/ 보호 된 무효 서비스 (httpservletrequest request, httpservletrepronse 응답) servletexception, ioexception {map <string, object> data = new Hashmap <string, object> (); data.put ( "날짜", 새 날짜 ()); data.put ( "이메일", "[email protected]"); data.put ( "Age", 30); data.put ( "name", "csdn"); data.put ( "array", new int [] {1,2,3,4}); responsejsonutils.json (응답, 데이터); }} /*** Servlets JSONP 형식 데이터*/@webservlet ( "/jsonp.do") 공개 클래스 jsonpservlet는 httpservlet을 확장합니다. /*** 요청은 콜백 함수로 콜백 매개 변수를 보냅니다. 콜백 매개 변수가 전송되지 않으면 기본 콜백 함수가 사용됩니다*/Protected void Service (httpservletrequest 요청, httpservletResponse 응답)는 servletexception, ioexception {// 클라이언트 문자열 콜백 = request.getParameter ( "콜백"); map <string, object> data = new Hashmap <String, object> (); data.put ( "날짜", 새 날짜 ()); data.put ( "이메일", "[email protected]"); data.put ( "Age", 30); data.put ( "name", "csdn"); data.put ( "array", new int [] {1,2,3,4}); if (callback == null || callback.length () == 0) {// 클라이언트가 콜백 함수를 보내지 않으면 기본 콜백 함수를 사용하지 않으면 replaysonutils.jsonp (응답, data); } else {// 클라이언트의 콜백 함수 사용 responskjsonutils.jsonp (응답, 콜백, 데이터); }}}} / ** * struts2에서 JSON 및 JSONP를 반환합니다./ public class jsonAction은 ActionSupport {private static final long serialversionUid = 5391000845385666048L; / *** JSONP 콜백 함수*/ 개인 문자열 콜백; / ** * 반환 json */ public void json () {httpservletResponse 응답 = servletActionContext.getResponse (); map <string, object> data = new Hashmap <String, object> (); data.put ( "날짜", 새 날짜 ()); data.put ( "이메일", "[email protected]"); data.put ( "Age", 30); data.put ( "name", "csdn"); data.put ( "array", new int [] {1,2,3,4}); responsejsonutils.json (응답, 데이터); } / ** * return JSONP * / public void jsonp () {httpservletResponse 응답 = servletActionContext.getResponse (); map <string, object> data = new Hashmap <String, object> (); data.put ( "날짜", 새 날짜 ()); data.put ( "이메일", "[email protected]"); data.put ( "Age", 30); data.put ( "name", "csdn"); data.put ( "array", new int [] {1,2,3,4}); if (callback == null || callback.length () == 0) {// 클라이언트가 콜백 함수를 보내지 않으면 기본 콜백 함수를 사용하지 않으면 replaysonutils.jsonp (응답, data); } else {// 클라이언트의 콜백 함수 사용 responskjsonutils.jsonp (응답, 콜백, 데이터); }} public String getCallback () {return 콜백; } public void setCallback (문자열 콜백) {this.callback = 콜백; }} org.springframework.steretype.controller import; org.springframework.web.bind.annotation.requestmapping; /*** Spring MVC는 JSON 및 JSONP 데이터를 반환합니다*/@Controller @RequestMapping ( "/json") 공개 클래스 JSONCONTROLLER {/*** return JSON DATA* @PARAM 요청* @Param 응답*/@RequestMapping ( "/json.do") 공개 void JSON (httppletRequest repured, httpervletRequest <map resong, data = new Hashmap <String, Object> (); data.put ( "날짜", 새 날짜 ()); data.put ( "이메일", "[email protected]"); data.put ( "Age", 30); data.put ( "name", "csdn"); data.put ( "array", new int [] {1,2,3,4}); responsejsonutils.json (응답, 데이터); }/*** jsonp data* @param 콜백 jsonp의 콜백 함수* @param request* @param response*/@requestmapping ( "/jsonp.do") public void json (문자열 콜백, httpservletrequest request request) {map <string, data = new Hashmap <string, object> (); data.put ( "날짜", 새 날짜 ()); data.put ( "이메일", "[email protected]"); data.put ( "Age", 30); data.put ( "name", "csdn"); data.put ( "array", new int [] {1,2,3,4}); if (callback == null || callback.length () == 0) {// 클라이언트가 콜백 함수를 보내지 않으면 기본 콜백 함수를 사용하지 않으면 replaysonutils.jsonp (응답, data); } else {// 클라이언트의 콜백 함수 사용 responskjsonutils.jsonp (응답, 콜백, 데이터); }}}