diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSON.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSON.java index 521acb01d..7bd24b97d 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSON.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSON.java @@ -60,21 +60,24 @@ public static String getCorrectJson(String s) { public static String getCorrectJson(String s, boolean isArray) { s = StringUtil.getTrimedString(s); // if (isArray) { - // if (s.startsWith("\"")) { + // while (s.startsWith("\"")) { // s = s.substring(1); // } - // if (s.endsWith("\"")) { + // while (s.endsWith("\"")) { // s = s.substring(0, s.length() - 1); // } // } return s;//isJsonCorrect(s) ? s : null; } - /**json转JSONObject + /**obj转JSONObject * @param json * @return */ public static JSONObject parseObject(Object obj) { + if (obj instanceof JSONObject) { + return (JSONObject) obj; + } return parseObject(toJSONString(obj)); } /**json转JSONObject @@ -114,12 +117,16 @@ public static T parseObject(JSONObject object, Class clazz) { * @return */ public static T parseObject(String json, Class clazz) { - try { - int features = com.alibaba.fastjson.JSON.DEFAULT_PARSER_FEATURE; - features |= Feature.OrderedField.getMask(); - return com.alibaba.fastjson.JSON.parseObject(getCorrectJson(json), clazz, features); - } catch (Exception e) { - Log.i(TAG, "parseObject catch \n" + e.getMessage()); + if (clazz == null) { + Log.e(TAG, "parseObject clazz == null >> return null;"); + } else { + try { + int features = com.alibaba.fastjson.JSON.DEFAULT_PARSER_FEATURE; + features |= Feature.OrderedField.getMask(); + return com.alibaba.fastjson.JSON.parseObject(getCorrectJson(json), clazz, features); + } catch (Exception e) { + Log.i(TAG, "parseObject catch \n" + e.getMessage()); + } } return null; } @@ -131,6 +138,16 @@ public static T parseObject(String json, Class clazz) { public static JSONArray parseArray(List list) { return new JSONArray(list); } + /**obj转JSONArray + * @param json + * @return + */ + public static JSONArray parseArray(Object obj) { + if (obj instanceof JSONArray) { + return (JSONArray) obj; + } + return parseArray(toJSONString(obj)); + } /**json转JSONArray * @param json * @return @@ -157,10 +174,14 @@ public static List parseArray(JSONArray array, Class clazz) { * @return */ public static List parseArray(String json, Class clazz) { - try { - return com.alibaba.fastjson.JSON.parseArray(getCorrectJson(json, true), clazz); - } catch (Exception e) { - Log.i(TAG, "parseArray catch \n" + e.getMessage()); + if (clazz == null) { + Log.e(TAG, "parseArray clazz == null >> return null;"); + } else { + try { + return com.alibaba.fastjson.JSON.parseArray(getCorrectJson(json, true), clazz); + } catch (Exception e) { + Log.i(TAG, "parseArray catch \n" + e.getMessage()); + } } return null; } diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSONObject.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSONObject.java index 4d3581764..3c9e0d1cf 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSONObject.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSONObject.java @@ -14,189 +14,49 @@ package zuo.biao.apijson; -import static zuo.biao.apijson.StringUtil.UTF_8; +import java.util.List; +import java.util.Map; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.Set; - -/**use this class instead of com.alibaba.fastjson.JSONObject, not encode in default cases +/**use this class instead of com.alibaba.fastjson.JSONObject * @author Lemon + * @see #put + * @see #puts + * @see #putsAll */ public class JSONObject extends com.alibaba.fastjson.JSONObject { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + private static final String TAG = "JSONObject"; + /**ordered */ public JSONObject() { super(true); } /**transfer Object to JSONObject - * encode = false; * @param object * @see {@link #JSONObject(Object, boolean)} */ public JSONObject(Object object) { - this(object, false); - } - /**transfer Object to JSONObject - * @param object - * @param encode - * @see {@link #JSONObject(String, boolean)} - */ - public JSONObject(Object object, boolean encode) { - this(toJSONString(object), encode); + this(toJSONString(object)); } /**parse JSONObject with JSON String - * encode = false; * @param json * @see {@link #JSONObject(String, boolean)} */ public JSONObject(String json) { - this(json, false); - } - /**parse JSONObject with JSON String - * @param json - * @param encode - * @see {@link #JSONObject(com.alibaba.fastjson.JSONObject, boolean)} - */ - public JSONObject(String json, boolean encode) { - this(parseObject(json), encode); + this(parseObject(json)); } /**transfer com.alibaba.fastjson.JSONObject to JSONObject - * encode = false; * @param object - * @see {@link #JSONObject(com.alibaba.fastjson.JSONObject, boolean)} + * @see {@link #putsAll(com.alibaba.fastjson.JSONObject)} */ public JSONObject(com.alibaba.fastjson.JSONObject object) { - this(object, false); - } - /**transfer com.alibaba.fastjson.JSONObject to JSONObject - * @param object - * @param encode - * @see {@link #add(com.alibaba.fastjson.JSONObject, boolean)} - */ - public JSONObject(com.alibaba.fastjson.JSONObject object, boolean encode) { this(); - add(object, encode); - } - - - - - /**put key-value in object into this - * encode = false; - * @param object - * @return {@link #add(com.alibaba.fastjson.JSONObject, boolean)} - */ - public JSONObject add(com.alibaba.fastjson.JSONObject object) { - return add(object, false); - } - /**put key-value in object into this - * @param object - * @param encode - * @return this - */ - public JSONObject add(com.alibaba.fastjson.JSONObject object, boolean encode) { - //TODO putAll(object); - - Set set = object == null ? null : object.keySet(); - if (set != null) { - for (String key : set) { - put(key, object.get(key), encode); - } - } - return this; - } - - - - /** - * @param key if decode && key instanceof String, key = URLDecoder.decode((String) key, UTF_8) - * @param decode if decode && value instanceof String, value = URLDecoder.decode((String) value, UTF_8) - * @return - */ - public Object get(Object key, boolean decode) { - if (decode) { - if (key instanceof String) { - if (((String) key).endsWith("+") || ((String) key).endsWith("-")) { - try {//多层encode导致内部Comment[]传到服务端decode后最终变为Comment%5B%5D - key = URLDecoder.decode((String) key, UTF_8); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return null; - } - } - } - Object value = super.get(key); - if (value instanceof String) { - try { - value = URLDecoder.decode((String) value, UTF_8); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - } - return value; - } - return super.get(key); + putsAll(object); } - /** - * encode = false - * @param value must be annotated by {@link APIJSONRequest} - * @return {@link #put(String, boolean)} - */ - public Object put(Object value) { - return put(value, false); - } - /** - * key = value.getClass().getSimpleName() - * @param value must be annotated by {@link APIJSONRequest} - * @param encode - * @return {@link #put(String, Object, boolean)} - */ - public Object put(Object value, boolean encode) { - return put(null, value, encode); - } - /** - * @param key if StringUtil.isNotEmpty(key, true) == false, - *
key = value == null ? null : value.getClass().getSimpleName(); - *
>> if decode && key instanceof String, key = URLDecoder.decode((String) key, UTF_8) - * @param value URLEncoder.encode((String) value, UTF_8); - * @param encode if value instanceof String, value = URLEncoder.encode((String) value, UTF_8); - * @return - */ - public Object put(String key, Object value, boolean encode) { - if (StringUtil.isNotEmpty(key, true) == false) { - Class clazz = value == null ? null : value.getClass(); - if (clazz == null || clazz.getAnnotation(MethodAccess.class) == null) { - throw new IllegalArgumentException("put StringUtil.isNotEmpty(key, true) == false" + - " && clazz == null || clazz.getAnnotation(MethodAccess.class) == null" + - " \n key为空时仅支持 类型被@MethodAccess注解 的value !!!" + - " \n 如果一定要这么用,请对 " + clazz.getName() + " 注解!" + - " \n 如果是类似 key[]:{} 结构的请求,建议add(...)方法!"); - } - key = value.getClass().getSimpleName(); - } - if (encode) { - if (key.endsWith("+") || key.endsWith("-")) { - try {//多层encode导致内部Comment[]传到服务端decode后最终变为Comment%5B%5D - key = URLEncoder.encode(key, UTF_8); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - } - if (value instanceof String) {//只在value instanceof String时encode key?{@link #get(Object, boolean)}内做不到 - try { - value = URLEncoder.encode((String) value, UTF_8); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - } - } - return super.put(key, value); - } @@ -215,38 +75,46 @@ public static boolean isArrayKey(String key) { * @return */ public static boolean isTableKey(String key) { - return StringUtil.isBigWord(key); + return StringUtil.isBigName(key); } //judge >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //JSONObject内关键词 key <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< - //@key关键字都放这个类 <<<<<<<<<<<<<<<<<<<<<< - /** - * 角色,拥有对某些数据的某些操作的权限 - */ - public static final String KEY_ROLE = "@role"; - /** - * 数据库,Table在非默认schema内时需要声明 - */ - public static final String KEY_SCHEMA = "@schema"; - /** - * 查询的Table字段或SQL函数 - */ - public static final String KEY_COLUMN = "@column"; - /** - * 分组方式 - */ - public static final String KEY_GROUP = "@group"; - /** - * 聚合函数条件,一般和@group一起用 + + public static final String KEY_ID = "id"; + public static final String KEY_ID_IN = KEY_ID + "{}"; + + /**set "id":id in Table layer + * @param id + * @return */ - public static final String KEY_HAVING = "@having"; - /** - * 排序方式 + public JSONObject setId(Long id) { + return puts(KEY_ID, id); + } + /**set id{}:[] in Table layer + * @param list + * @return */ - public static final String KEY_ORDER = "@order"; + public JSONObject setIdIn(List list) { + return puts(KEY_ID_IN, list); + } + + + //@key关键字都放这个类 <<<<<<<<<<<<<<<<<<<<<< + public static final String KEY_ROLE = "@role"; //角色,拥有对某些数据的某些操作的权限 + public static final String KEY_CONDITION = "@condition"; //条件 TODO 用 @where& @where| @where! 替代? + public static final String KEY_TRY = "@try"; //尝试,忽略异常 + public static final String KEY_DROP = "@drop"; //丢弃,不返回 + public static final String KEY_CORRECT = "@correct"; //字段校正 + + public static final String KEY_SCHEMA = "@schema"; //数据库,Table在非默认schema内时需要声明 + public static final String KEY_ABOUT = "@about"; //关于,返回数据库表的信息,包括表说明和字段说明 + public static final String KEY_COLUMN = "@column"; //查询的Table字段或SQL函数 + public static final String KEY_GROUP = "@group"; //分组方式 + public static final String KEY_HAVING = "@having"; //聚合函数条件,一般和@group一起用 + public static final String KEY_ORDER = "@order"; //排序方式 //@key关键字都放这个类 >>>>>>>>>>>>>>>>>>>>>> @@ -255,17 +123,49 @@ public static boolean isTableKey(String key) { * @return this */ public JSONObject setRole(String role) { - put(KEY_ROLE, role); - return this; + return puts(KEY_ROLE, role); + } + + /**set try, ignore exceptions + * @param tri + * @return this + */ + public JSONObject setTry(boolean tri) { + return puts(KEY_TRY, tri); } + + /**set drop, data dropped will not return + * @param drop + * @return this + */ + public JSONObject setDrop(boolean drop) { + return puts(KEY_DROP, drop); + } + + /**set correct, correct keys to target ones + * @param correct Map{originKey, [posibleKeys]}, posibleKey之间用 , 隔开 + * @return this + */ + public JSONObject setCorrect(Map correct) { + return puts(KEY_CORRECT, correct); + } + + - /**set schema where table was put + /**set schema where table was puts * @param schema * @return this */ public JSONObject setSchema(String schema) { - put(KEY_SCHEMA, schema); - return this; + return puts(KEY_SCHEMA, schema); + } + + /**set about + * @param about + * @return this + */ + public JSONObject setAbout(boolean about) { + return puts(KEY_ABOUT, about); } /**set keys need to be returned @@ -280,8 +180,7 @@ public JSONObject setColumn(String... keys) { * @return */ public JSONObject setColumn(String keys) { - put(KEY_COLUMN, keys); - return this; + return puts(KEY_COLUMN, keys); } /**set keys for group by @@ -296,8 +195,7 @@ public JSONObject setGroup(String... keys) { * @return */ public JSONObject setGroup(String keys) { - put(KEY_GROUP, keys); - return this; + return puts(KEY_GROUP, keys); } /**set keys for having @@ -312,8 +210,7 @@ public JSONObject setHaving(String... keys) { * @return */ public JSONObject setHaving(String keys) { - put(KEY_HAVING, keys); - return this; + return puts(KEY_HAVING, keys); } /**set keys for order by @@ -328,8 +225,7 @@ public JSONObject setOrder(String... keys) { * @return */ public JSONObject setOrder(String keys) { - put(KEY_ORDER, keys); - return this; + return puts(KEY_ORDER, keys); } @@ -337,117 +233,142 @@ public JSONObject setOrder(String keys) { - //Request,默认encode <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< + //Request <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< /** - * encode = true - * @param value - * @param parts path = keys[0] + "/" + keys[1] + "/" + keys[2] + ... - * @return #put(key+"@", StringUtil.getString(keys, "/"), true) - */ - public Object putPath(String key, String... keys) { - return put(key+"@", StringUtil.getString(keys, "/"), true); - } - - /** - * encode = true * @param key - * @param isNull - * @return {@link #putNull(String, boolean, boolean)} + * @param keys path = keys[0] + "/" + keys[1] + "/" + keys[2] + ... + * @return {@link #puts(String, Object)} */ - public JSONObject putNull(String key, boolean isNull) { - return putNull(key, isNull, true); + public JSONObject putsPath(String key, String... keys) { + return puts(key+"@", StringUtil.getString(keys, "/")); } + /** * @param key * @param isNull - * @param encode - * @return put(key+"{}", SQL.isNull(isNull), encode); + * @return {@link #puts(String, Object)} */ - public JSONObject putNull(String key, boolean isNull, boolean encode) { - put(key+"{}", SQL.isNull(isNull), encode); - return this; + public JSONObject putsNull(String key, boolean isNull) { + return puts(key+"{}", SQL.isNull(isNull)); } /** * trim = false * @param key * @param isEmpty - * @return {@link #putEmpty(String, boolean, boolean)} + * @return {@link #putsEmpty(String, boolean, boolean)} */ - public JSONObject putEmpty(String key, boolean isEmpty) { - return putEmpty(key, isEmpty, false); + public JSONObject putsEmpty(String key, boolean isEmpty) { + return putsEmpty(key, isEmpty, false); } /** - * encode = true * @param key * @param isEmpty - * @return {@link #putEmpty(String, boolean, boolean, boolean)} - */ - public JSONObject putEmpty(String key, boolean isEmpty, boolean trim) { - return putEmpty(key, isEmpty, trim, true); - } - /** - * @param key - * @param isEmpty - * @param encode - * @return put(key+"{}", SQL.isEmpty(key, isEmpty, trim), encode); - */ - public JSONObject putEmpty(String key, boolean isEmpty, boolean trim, boolean encode) { - put(key+"{}", SQL.isEmpty(key, isEmpty, trim), encode); - return this; - } - /** - * encode = true - * @param key - * @param compare <=0, >5 ... - * @return {@link #putLength(String, String, boolean)} + * @return {@link #puts(String, Object)} */ - public JSONObject putLength(String key, String compare) { - return putLength(key, compare, true); + public JSONObject putsEmpty(String key, boolean isEmpty, boolean trim) { + return puts(key+"{}", SQL.isEmpty(key, isEmpty, trim)); } /** * @param key * @param compare <=0, >5 ... - * @param encode - * @return put(key+"{}", SQL.length(key) + compare, encode); + * @return {@link #puts(String, Object)} */ - public JSONObject putLength(String key, String compare, boolean encode) { - put(key+"{}", SQL.length(key) + compare, encode); - return this; + public JSONObject putsLength(String key, String compare) { + return puts(key+"{}", SQL.length(key) + compare); } /**设置搜索 * type = SEARCH_TYPE_CONTAIN_FULL * @param key * @param value - * @return {@link #putSearch(String, String, int)} + * @return {@link #putsSearch(String, String, int)} */ - public JSONObject putSearch(String key, String value) { - return putSearch(key, value, SQL.SEARCH_TYPE_CONTAIN_FULL); + public JSONObject putsSearch(String key, String value) { + return putsSearch(key, value, SQL.SEARCH_TYPE_CONTAIN_FULL); } /**设置搜索 - * encode = true * @param key * @param value * @param type - * @return {@link #putSearch(String, String, int, boolean)} + * @return {@link #puts(String, Object)} */ - public JSONObject putSearch(String key, String value, int type) { - return putSearch(key, value, type, true); + public JSONObject putsSearch(String key, String value, int type) { + return puts(key+"$", SQL.search(value, type)); } - /**设置搜索 + + //Request >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + + + + /**puts key-value in object into this + * @param object + * @return this + */ + public JSONObject putsAll(Map map) { + putAll(map); + return this; + } + @Override + public void putAll(Map map) { + if (map != null && map.isEmpty() == false) { + super.putAll(map); + } + } + + + + /**put and return this + * @param value must be annotated by {@link MethodAccess} + * @return {@link #puts(String, boolean)} + */ + public JSONObject puts(Object value) { + return puts(null, value); + } + /**put and return this * @param key - * @param value - * @param type - * @param encode - * @return put(key+"$", SQL.search(value, type), encode); + * @param value + * @return this + * @see {@link #put(String, Object)} */ - public JSONObject putSearch(String key, String value, int type, boolean encode) { - put(key+"$", SQL.search(value, type), encode); + public JSONObject puts(String key, Object value) { + put(key, value); return this; } + + /**put and return value + * @param value must be annotated by {@link MethodAccess} + * @return {@link #put(String, boolean)} + */ + public Object put(Object value) { + return put(null, value); + } + /**put and return value + * @param key StringUtil.isEmpty(key, true) ? key = value.getClass().getSimpleName(); + * @param value + * @return value + */ + @Override + public Object put(String key, Object value) { + if (value == null) { + Log.e(TAG, "put value == null >> return null;"); + return null; + } + if (StringUtil.isEmpty(key, true)) { + Class clazz = value.getClass(); + if (clazz == null || clazz.getAnnotation(MethodAccess.class) == null) { + throw new IllegalArgumentException("puts StringUtil.isNotEmpty(key, true) == false" + + " && clazz == null || clazz.getAnnotation(MethodAccess.class) == null" + + " \n key为空时仅支持 类型被@MethodAccess注解 的value !!!" + + " \n 如果一定要这么用,请对 " + clazz.getName() + " 注解!" + + " \n 如果是类似 key[]:{} 结构的请求,建议用 putsAll(...) !"); + } + key = value.getClass().getSimpleName(); + } + return super.put(key, value); + } - //Request,默认encode >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + } diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSONRequest.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSONRequest.java index 78b935560..5d33b681d 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSONRequest.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSONRequest.java @@ -14,11 +14,14 @@ package zuo.biao.apijson; -/**encapsulator for request JSONObject, encode in default cases +import java.util.Map; + +/**wrapper for request * @author Lemon + * @see #puts * @see #toArray * @use JSONRequest request = new JSONRequest(...); - *
request.put(...);//not a must + *
request.puts(...);//not a must *
request.toArray(...);//not a must */ public class JSONRequest extends JSONObject { @@ -28,51 +31,34 @@ public JSONRequest() { super(); } /** - * encode = true - * @param object must be annotated by {@link APIJSONRequest} + * @param object must be annotated by {@link MethodAccess} * @see {@link #JSONRequest(String, Object)} */ public JSONRequest(Object object) { this(null, object); } /** - * encode = true * @param name * @param object - * @see {@link #JSONRequest(String, Object, boolean)} + * @see {@link #puts(String, Object)} */ public JSONRequest(String name, Object object) { - this(name, object, true); - } - /** - * @param object must be annotated by {@link APIJSONRequest} - * @param encode - * @see {@link #JSONRequest(String, Object, boolean)} - */ - public JSONRequest(Object object, boolean encode) { - this(null, object, encode); - } - /** - * @param name - * @param object - * @param encode - * @see {@link #put(String, Object, boolean)} - */ - public JSONRequest(String name, Object object, boolean encode) { this(); - put(name, object, encode); + puts(name, object); } - - - + public static final String KEY_TAG = "tag";//只在最外层,最外层用JSONRequest - - public JSONObject setTag(String tag) { - put(KEY_TAG, tag); - return this; + + /**set "tag":tag in outermost layer + * for write operations + * @param tag + * @return + */ + public JSONRequest setTag(String tag) { + return puts(KEY_TAG, tag); } @@ -86,104 +72,67 @@ public JSONObject setTag(String tag) { public static final String KEY_COUNT = "count"; public static final String KEY_PAGE = "page"; - /** + /**set what to query in Array layer * @param query what need to query, Table,total,ALL? * @return + * @see {@link #QUERY_TABLE} + * @see {@link #QUERY_TOTAL} + * @see {@link #QUERY_ALL} */ public JSONRequest setQuery(int query) { - put(KEY_QUERY, query); - return this; + return puts(KEY_QUERY, query); } - /** - * @param count + /**set maximum count of Tables to query in Array layer + * @param count <= 0 || >= max ? max : count * @return */ public JSONRequest setCount(int count) { - put(KEY_COUNT, count); - return this; + return puts(KEY_COUNT, count); } - /** - * @param page + /**set page of Tables to query in Array layer + * @param page <= 0 ? 0 : page * @return */ public JSONRequest setPage(int page) { - put(KEY_PAGE, page); - return this; + return puts(KEY_PAGE, page); } //array object >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> - - // 导致JSONObject add >> get = null - // /** - // * decode = true - // * @param key - // * return {@link #get(Object, boolean)} - // */ - // @Override - // public Object get(Object key) { - // return get(key, true); - // } - - /** - * encode = true - * @param value must be annotated by {@link APIJSONRequest} - * @return {@link #put(String, boolean)} - */ - @Override - public Object put(Object value) { - return put(value, true); - } - /** - * encode = true - * @param key - * @param value - * return {@link #put(String, Object, boolean)} - */ - @Override - public Object put(String key, Object value) { - return put(key, value, true); - } - - /**create a parent JSONObject named KEY_ARRAY - * encode = true; * @param count * @param page * @return {@link #toArray(int, int, boolean)} */ public JSONRequest toArray(int count, int page) { - return toArray(count, page, true); - } - /**create a parent JSONObject named KEY_ARRAY - * encode = true; - * @param count - * @param page - * @return {@link #toArray(int, int, String, boolean)} - */ - public JSONRequest toArray(int count, int page, boolean encode) { - return toArray(count, page, null, encode); - } - /**create a parent JSONObject named name+KEY_ARRAY - * encode = true; - * @param count - * @param page - * @param name - * @return {@link #toArray(int, int, String, boolean)} - */ - public JSONRequest toArray(int count, int page, String name) { - return toArray(count, page, name, true); + return toArray(count, page, null); } /**create a parent JSONObject named name+KEY_ARRAY. * @param count * @param page * @param name - * @param encode * @return {name+KEY_ARRAY : this}. if needs to be put, use {@link #add(com.alibaba.fastjson.JSONObject)} instead */ - public JSONRequest toArray(int count, int page, String name, boolean encode) { - return new JSONRequest(StringUtil.getString(name) + KEY_ARRAY, this.setCount(count).setPage(page), encode); + public JSONRequest toArray(int count, int page, String name) { + return new JSONRequest(StringUtil.getString(name) + KEY_ARRAY, this.setCount(count).setPage(page)); + } + + + @Override + public JSONObject putsAll(Map map) { + super.putsAll(map); + return this; + } + + @Override + public JSONRequest puts(Object value) { + return puts(null, value); + } + @Override + public JSONRequest puts(String key, Object value) { + super.puts(key, value); + return this; } } diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSONResponse.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSONResponse.java index 1135a3f9e..f9b6d3fc9 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSONResponse.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/JSONResponse.java @@ -20,17 +20,16 @@ import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; -/**parser for response JSON String +/**parser for response * @author Lemon + * @see #getObject * @see #getList - * @see #toArray * @use JSONResponse response = new JSONResponse(json); - *
JSONArray array = JSONResponse.toArray(response.getJSONObject("[]"));//not a must - *
User user = JSONResponse.getObject(response, User.class);//not a must - *
List list = JSONResponse.getList(response.getJSONObject("Comment[]"), Comment.class);//not a must + *
User user = response.getObject(User.class);//not a must + *
List commenntList = response.getList("Comment[]", Comment.class);//not a must */ public class JSONResponse extends zuo.biao.apijson.JSONObject { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private static final String TAG = "JSONResponse"; @@ -46,26 +45,30 @@ public JSONResponse(JSONObject object) { //状态信息,非GET请求获得的信息<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< - public static final int CODE_SUCCEED = 200; - public static final int CODE_PARTIAL_SUCCEED = 206; - public static final int CODE_UNSUPPORTED_ENCODING = 400; - public static final int CODE_ILLEGAL_ACCESS = 401; - public static final int CODE_UNSUPPORTED_OPERATION = 403; - public static final int CODE_NOT_FOUND = 404; - public static final int CODE_ILLEGAL_ARGUMENT = 406; - public static final int CODE_NOT_LOGGED_IN = 407; - public static final int CODE_TIME_OUT = 408; - public static final int CODE_CONFLICT = 409; - public static final int CODE_CONDITION_ERROR = 412; - public static final int CODE_UNSUPPORTED_TYPE = 415; - public static final int CODE_OUT_OF_RANGE = 416; - public static final int CODE_NULL_POINTER = 417; - public static final int CODE_SERVER_ERROR = 500; - - + public static final int CODE_SUCCESS = 200; //成功 + public static final int CODE_UNSUPPORTED_ENCODING = 400; //编码错误 + public static final int CODE_ILLEGAL_ACCESS = 401; //权限错误 + public static final int CODE_UNSUPPORTED_OPERATION = 403; //禁止操作 + public static final int CODE_NOT_FOUND = 404; //未找到 + public static final int CODE_ILLEGAL_ARGUMENT = 406; //参数错误 + public static final int CODE_NOT_LOGGED_IN = 407; //未登录 + public static final int CODE_TIME_OUT = 408; //超时 + public static final int CODE_CONFLICT = 409; //重复,已存在 + public static final int CODE_CONDITION_ERROR = 412; //条件错误,如密码错误 + public static final int CODE_UNSUPPORTED_TYPE = 415; //类型错误 + public static final int CODE_OUT_OF_RANGE = 416; //超出范围 + public static final int CODE_NULL_POINTER = 417; //对象为空 + public static final int CODE_SERVER_ERROR = 500; //服务器内部错误 + + + public static final String MSG_SUCCEED = "success"; //成功 + public static final String MSG_SERVER_ERROR = "Internal Server Error!"; //服务器内部错误 + + public static final String KEY_CODE = "code"; public static final String KEY_MSG = "msg"; public static final String KEY_ID = "id"; + public static final String KEY_ID_IN = KEY_ID + "{}"; public static final String KEY_COUNT = "count"; public static final String KEY_TOTAL = "total"; @@ -124,22 +127,22 @@ public int getTotal() { /**是否成功 * @return */ - public boolean isSucceed() { - return isSucceed(getCode()); + public boolean isSuccess() { + return isSuccess(getCode()); } /**是否成功 * @param code * @return */ - public static boolean isSucceed(int code) { - return code == CODE_SUCCEED; + public static boolean isSuccess(int code) { + return code == CODE_SUCCESS; } /**是否成功 * @param response * @return */ - public static boolean isSucceed(JSONResponse response) { - return response != null && response.isSucceed(); + public static boolean isSuccess(JSONResponse response) { + return response != null && response.isSuccess(); } /**校验服务端是否存在table @@ -256,213 +259,110 @@ public static List getList(JSONObject object, Class clazz) { * @return */ public static List getList(JSONObject object, String key, Class clazz) { - Object obj = object == null ? null : object.get(replaceArray(key)); - if (obj == null) { - return null; - } - return obj instanceof JSONArray ? JSON.parseArray((JSONArray) obj, clazz) : toList((JSONObject) obj, clazz); - } - /** - * @param clazz - * @return - */ - public List toList(Class clazz) { - return toList(this, clazz); - } - /** - * @param arrayObject - * @param clazz - * @return - */ - public static List toList(JSONObject arrayObject, Class clazz) { - return clazz == null ? null : JSON.parseArray(JSON.toJSONString( - toArray(arrayObject, clazz.getSimpleName())), clazz); + return object == null ? null : JSON.parseArray(object.getString(replaceArray(key)), clazz); } /** * key = KEY_ARRAY - * @param className * @return */ - public JSONArray getArray(String className) { - return getArray(KEY_ARRAY, className); + public JSONArray getArray() { + return getArray(KEY_ARRAY); } /** * @param key - * @param className * @return */ - public JSONArray getArray(String key, String className) { - return getArray(this, key, className); + public JSONArray getArray(String key) { + return getArray(this, key); } /** * @param object - * @param key - * @param className * @return */ - public static JSONArray getArray(JSONObject object, String className) { - return getArray(object, KEY_ARRAY, className); + public static JSONArray getArray(JSONObject object) { + return getArray(object, KEY_ARRAY); } /** * key = KEY_ARRAY * @param object - * @param className - * @return - */ - public static JSONArray getArray(JSONObject object, String key, String className) { - Object obj = object == null ? null : object.get(replaceArray(key)); - if (obj == null) { - return null; - } - return obj instanceof JSONArray ? (JSONArray) obj : toArray((JSONObject) obj, className); - } - - /** - * @param className - * @return - */ - public JSONArray toArray(String className) { - return toArray(this, className); - } - /**{0:{Table:{}}, 1:{Table:{}}...} 转化为 [{Table:{}}, {Table:{}}] - * array.set(index, isContainer ? value : value.getJSONObject(className)); - * @param arrayObject - * @param className className.equals(Table) ? {Table:{Content}} => {Content} + * @param key * @return */ - public static JSONArray toArray(JSONObject arrayObject, String className) { - Set set = arrayObject == null ? null : arrayObject.keySet(); - if (set == null || set.isEmpty()) { - return null; - } - - // [{...},{...},...] - String parentString = StringUtil.getTrimedString(JSON.toJSONString(arrayObject)); - if (parentString.isEmpty()) { - return null; - } - if (parentString.startsWith("[")) { - if (parentString.endsWith("]") == false) { - parentString += "]"; - } - return JSON.parseArray(parentString); - } - - //{"0":{Table:{...}}, "1":{Table:{...}}...} - - className = StringUtil.getTrimedString(className); - boolean isContainer = true; - - JSONArray array = new JSONArray(set.size()); - JSONObject value; - boolean isFirst = true; - int index; - for (String key : set) {//0, 1, 2,... - value = StringUtil.isNumer(key) == false ? null : arrayObject.getJSONObject(key);// Table:{} - if (value != null) { - try { - index = Integer.valueOf(0 + key); - if (isFirst && isTableKey(className) && value.containsKey(className)) {// 判断是否需要提取table - isContainer = false; - } - array.set(index, isContainer ? value : value.getJSONObject(className)); - } catch (Exception e) { - e.printStackTrace(); - } - } - isFirst = false; - } - return array; + public static JSONArray getArray(JSONObject object, String key) { + return object == null ? null : object.getJSONArray(replaceArray(key)); } - // /** // * @return // */ // public JSONObject format() { // return format(this); // } - /**将Item[]:[{Table:{}}, {Table:{}}...] 或 Item[]:{0:{Table:{}}, 1:{Table:{}}...} - * 转化为 itemList:[{Table:{}}, {Table:{}}],如果 Item.equals(Table),则将 {Table:{Content}} 转化为 {Content} - * @param target - * @param response + /**格式化key名称 + * @param object * @return */ - public static JSONObject format(final JSONObject response) { - //太长查看不方便,不如debug Log.i(TAG, "format response = \n" + JSON.toJSONString(response)); - if (response == null || response.isEmpty()) { - Log.i(TAG, "format response == null || response.isEmpty() >> return response;"); - return response; + public static JSONObject format(final JSONObject object) { + //太长查看不方便,不如debug Log.i(TAG, "format object = \n" + JSON.toJSONString(object)); + if (object == null || object.isEmpty()) { + Log.i(TAG, "format object == null || object.isEmpty() >> return object;"); + return object; } - JSONObject transferredObject = new JSONObject(true); + JSONObject formatedObject = new JSONObject(true); - Set set = response.keySet(); + Set set = object.keySet(); if (set != null) { Object value; - String arrayKey; for (String key : set) { - value = response.get(key); - - if (value instanceof JSONArray) {//转化JSONArray内部的APIJSON Array - transferredObject.put(replaceArray(key), format(key, (JSONArray) value)); - } else if (value instanceof JSONObject) {//APIJSON Array转为常规JSONArray - if (isArrayKey(key)) {//APIJSON Array转为常规JSONArray - arrayKey = key.substring(0, key.lastIndexOf(KEY_ARRAY)); - transferredObject.put(getArrayKey(getSimpleName(arrayKey)) - , format(key, toArray((JSONObject) value, arrayKey)));//需要将name:alias传至toArray - } else {//常规JSONObject,往下一级提取 - transferredObject.put(getSimpleName(key), format((JSONObject) value)); - } - } else {//其它Object,直接填充 - transferredObject.put(getSimpleName(key), value); + value = object.get(key); + + if (value instanceof JSONArray) {//JSONArray,遍历来format内部项 + formatedObject.put(replaceArray(key), format((JSONArray) value)); + } + else if (value instanceof JSONObject) {//JSONObject,往下一级提取 + formatedObject.put(getSimpleName(key), format((JSONObject) value)); + } + else {//其它Object,直接填充 + formatedObject.put(getSimpleName(key), value); } } } - //太长查看不方便,不如debug Log.i(TAG, "format return transferredObject = " + JSON.toJSONString(transferredObject)); - return transferredObject; + //太长查看不方便,不如debug Log.i(TAG, "format return formatedObject = " + JSON.toJSONString(formatedObject)); + return formatedObject; } - /** - * @param responseArray + /**格式化key名称 + * @param array * @return */ - public static JSONArray format(String name, final JSONArray responseArray) { - //太长查看不方便,不如debug Log.i(TAG, "format responseArray = \n" + JSON.toJSONString(responseArray)); - if (responseArray == null || responseArray.isEmpty()) { - Log.i(TAG, "format responseArray == null || responseArray.isEmpty() >> return response;"); - return responseArray; + public static JSONArray format(final JSONArray array) { + //太长查看不方便,不如debug Log.i(TAG, "format array = \n" + JSON.toJSONString(array)); + if (array == null || array.isEmpty()) { + Log.i(TAG, "format array == null || array.isEmpty() >> return array;"); + return array; } - int index = name == null ? -1 : name.lastIndexOf(KEY_ARRAY); - String className = index < 0 ? "" : name.substring(0, index); - - JSONArray transferredArray = new JSONArray(); + JSONArray formatedArray = new JSONArray(); Object value; - boolean isContainer = true; - boolean isFirst = true; - for (int i = 0; i < responseArray.size(); i++) { - value = responseArray.get(i); - if (value instanceof JSONArray) {//转化JSONArray内部的APIJSON Array - transferredArray.add(format(null, (JSONArray) value)); - } else if (value instanceof JSONObject) {//JSONObject,往下一级提取 - //判断是否需要提取child - if (isFirst && isTableKey(className) && ((JSONObject) value).containsKey(className)) { - isContainer = false; - } - //直接添加child 或 添加提取出的child - transferredArray.add(format(isContainer ? (JSONObject)value : ((JSONObject)value).getJSONObject(className) )); - isFirst = false; - } else {//其它Object,直接填充 - transferredArray.add(responseArray.get(i)); + for (int i = 0; i < array.size(); i++) { + value = array.get(i); + if (value instanceof JSONArray) {//JSONArray,遍历来format内部项 + formatedArray.add(format((JSONArray) value)); + } + else if (value instanceof JSONObject) {//JSONObject,往下一级提取 + formatedArray.add(format((JSONObject) value)); + } + else {//其它Object,直接填充 + formatedArray.add(value); } } - //太长查看不方便,不如debug Log.i(TAG, "format return transferredArray = " + JSON.toJSONString(transferredArray)); - return transferredArray; + //太长查看不方便,不如debug Log.i(TAG, "format return formatedArray = " + JSON.toJSONString(formatedArray)); + return formatedArray; } /**替换key+KEY_ARRAY为keyList @@ -485,7 +385,7 @@ public static String getArrayKey(String key) { /**获取简单名称 * @param fullName name 或 name:alias - * @return name > name; name:alias > alias + * @return name => name; name:alias => alias */ public static String getSimpleName(String fullName) { //key:alias -> alias; key:alias[] -> alias[] diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/MethodAccess.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/MethodAccess.java index 1cf14dc6e..c69f55ac7 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/MethodAccess.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/MethodAccess.java @@ -36,37 +36,37 @@ public @interface MethodAccess { /**@see {@link RequestMethod#GET} - * @return 该请求方法允许的结构 default {UNKNOWN, LOGIN, CONTACT, CIRCLE, OWNER, ADMIN}; + * @return 该请求方法允许的角色 default {UNKNOWN, LOGIN, CONTACT, CIRCLE, OWNER, ADMIN}; */ RequestRole[] GET() default {UNKNOWN, LOGIN, CONTACT, CIRCLE, OWNER, ADMIN}; /**@see {@link RequestMethod#HEAD} - * @return 该请求方法允许的结构 default {UNKNOWN, LOGIN, CONTACT, CIRCLE, OWNER, ADMIN}; + * @return 该请求方法允许的角色 default {UNKNOWN, LOGIN, CONTACT, CIRCLE, OWNER, ADMIN}; */ RequestRole[] HEAD() default {UNKNOWN, LOGIN, CONTACT, CIRCLE, OWNER, ADMIN}; /**@see {@link RequestMethod#POST_GET} - * @return 该请求方法允许的结构 default {LOGIN, CONTACT, CIRCLE, OWNER, ADMIN}; + * @return 该请求方法允许的角色 default {LOGIN, CONTACT, CIRCLE, OWNER, ADMIN}; */ RequestRole[] POST_GET() default {LOGIN, CONTACT, CIRCLE, OWNER, ADMIN}; /**@see {@link RequestMethod#POST_HEAD} - * @return 该请求方法允许的结构 default {LOGIN, CONTACT, CIRCLE, OWNER, ADMIN}; + * @return 该请求方法允许的角色 default {LOGIN, CONTACT, CIRCLE, OWNER, ADMIN}; */ RequestRole[] POST_HEAD() default {LOGIN, CONTACT, CIRCLE, OWNER, ADMIN}; /**@see {@link RequestMethod#POST} - * @return 该请求方法允许的结构 default {LOGIN, ADMIN}; + * @return 该请求方法允许的角色 default {LOGIN, ADMIN}; */ RequestRole[] POST() default {LOGIN, ADMIN}; /**@see {@link RequestMethod#PUT} - * @return 该请求方法允许的结构 default {OWNER, ADMIN}; + * @return 该请求方法允许的角色 default {OWNER, ADMIN}; */ RequestRole[] PUT() default {OWNER, ADMIN}; /**@see {@link RequestMethod#DELETE} - * @return 该请求方法允许的结构 default {OWNER, ADMIN}; + * @return 该请求方法允许的角色 default {OWNER, ADMIN}; */ RequestRole[] DELETE() default {OWNER, ADMIN}; diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/RequestMethod.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/RequestMethod.java index 11f928134..13182f99d 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/RequestMethod.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/RequestMethod.java @@ -29,13 +29,13 @@ public enum RequestMethod { */ HEAD, - /** - * 通过POST来GET数据,不显示请求内容和返回结果,一般用于对安全要求比较高的请求 + /**TODO 改为GETS + * 通过POST来GET数据,不显示请求内容和返回结果,并且校验请求,一般用于对安全要求比较高的请求 */ POST_GET, - /** - * 通过POST来HEAD数据,不显示请求内容和返回结果,一般用于对安全要求比较高的请求 + /**TODO 改为HEADS + * 通过POST来HEAD数据,不显示请求内容和返回结果,并且校验请求,一般用于对安全要求比较高的请求 */ POST_HEAD, diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/SQL.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/SQL.java index 63f532b52..a9da023e5 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/SQL.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/SQL.java @@ -22,8 +22,16 @@ public class SQL { public static final String OR = " OR "; public static final String AND = " AND "; public static final String NOT = " NOT "; + public static final String AS = " AS "; public static final String IS = " is "; public static final String NULL = " null "; + + //括号必须紧跟函数名! count (...) 报错! + public static final String COUNT = "count"; + public static final String SUM = "sum"; + public static final String MAX = "max"; + public static final String MIN = "min"; + public static final String AVG = "avg"; /** * isNull = true @@ -34,7 +42,7 @@ public static String isNull() { } /** * @param isNull - * @return IS + (isNull ? "" : NOT) + NULL; + * @return {@link #IS} + (isNull ? "" : {@link #NOT}) + {@link #NULL}; */ public static String isNull(boolean isNull) { return IS + (isNull ? "" : NOT) + NULL; @@ -87,7 +95,7 @@ public static String isEmpty(String s, boolean isEmpty, boolean trim) { * @param s * @param isEmpty <=0 * @param trim s = trim(s); - * @param nullable isNull(s, true) + OR + + * @param nullable isNull(s, true) + {@link #OR} + * @return {@link #lengthCompare(String, String)} */ public static String isEmpty(String s, boolean isEmpty, boolean trim, boolean nullable) { @@ -171,30 +179,30 @@ public static String subString(String s, int start, int end) { /** * @param s - * @param c - * @return "instr(" + s + "," + c + ")" + * @param c -> 'c' + * @return "instr(" + s + ", '" + c + "')" */ public static String indexOf(String s, String c) { - return "instr(" + s + "," + c + ")"; + return "instr(" + s + ", '" + c + "')"; } /** * @param s - * @param c1 - * @param c2 - * @return + * @param c1 -> 'c1' + * @param c2 -> 'c2' + * @return "replace(" + s + ", '" + c1 + "', '" + c2 + "')" */ public static String replace(String s, String c1, String c2) { - return "replace(" + s + "," + c1 + "," + c2 + ")"; + return "replace(" + s + ", '" + c1 + "', '" + c2 + "')"; } /** * @param s1 - * @param s2 - * @return "strcmp(" + s1 + "," + s2 + ")" + * @param s2 -> 's2' + * @return "strcmp(" + s1 + ", '" + s2 + "')" */ public static String equals(String s1, String s2) { - return "strcmp(" + s1 + "," + s2 + ")"; + return "strcmp(" + s1 + ", '" + s2 + "')"; } /** @@ -212,9 +220,98 @@ public static String toLowerCase(String s) { return "lower(" + s + ")"; } + + + //column and function<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< + + /**字段 + * @param column + * @return column.isEmpty() ? "*" : column; + */ + public static String column(String column) { + column = StringUtil.getTrimedString(column); + return column.isEmpty() ? "*" : column; + } + /**有别名的字段 + * @param column + * @return {@link #count(String)} + {@link #AS}; + */ + public static String columnAs(String column) { + return count(column) + AS; + } + + /**函数 + * @param column if (StringUtil.isEmpty(column, true) || column.contains(",")) -> column = null; + * @return " " + fun + "(" + {@link #column(String)} + ") "; + */ + public static String function(String fun, String column) { + if (StringUtil.isEmpty(column, true) || column.contains(",")) { + column = null; //解决 count(id,name) 这种多个字段导致的SQL异常 + } + return " " + fun + "(" + column(column) + ") "; + } + /**有别名的函数 + * @param column + * @return {@link #function(String, String)} + {@link #AS} + fun; + */ + public static String functionAs(String fun, String column) { + return function(fun, column) + AS + fun + " "; + } + + /**计数 + * column = null + * @return {@link #count(String)} + */ + public static String count() { + return count(null); + } + /**计数 + * fun = {@link #COUNT} + * @param column + * @return {@link #functionAs(String, String)} + */ + public static String count(String column) { + return functionAs(COUNT, column); + } + /**求和 + * fun = {@link #SUM} + * @param column + * @return {@link #functionAs(String, String)} + */ + public static String sum(String column) { + return functionAs(SUM, column); + } + /**最大值 + * fun = {@link #MAX} + * @param column + * @return {@link #functionAs(String, String)} + */ + public static String max(String column) { + return functionAs(MAX, column); + } + /**最小值 + * fun = {@link #MIN} + * @param column + * @return {@link #functionAs(String, String)} + */ + public static String min(String column) { + return functionAs(MIN, column); + } + /**平均值 + * fun = {@link #AVG} + * @param column + * @return {@link #functionAs(String, String)} + */ + public static String avg(String column) { + return functionAs(AVG, column); + } - + //column and function>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + + + + //search<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< public static final int SEARCH_TYPE_CONTAIN_FULL = 0; public static final int SEARCH_TYPE_CONTAIN_ORDER = 1; @@ -286,5 +383,7 @@ public static String search(String s, int type, boolean ignoreCase) { return "%" + s + "%"; } } + + //search>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> } diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/StringUtil.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/StringUtil.java index 538db3e06..205d6436f 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/StringUtil.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/StringUtil.java @@ -17,7 +17,6 @@ import java.io.File; import java.math.BigDecimal; import java.text.DecimalFormat; -import java.util.regex.Matcher; import java.util.regex.Pattern; /**通用字符串(String)相关类,为null时返回"" @@ -100,7 +99,7 @@ public static String getString(String s) { * @param array * @return {@link #getString(String[], boolean)} */ - public static String getString(String[] array) { + public static String getString(Object[] array) { return getString(array, false); } /**获取string,为null则返回"" @@ -109,7 +108,7 @@ public static String getString(String[] array) { * @param ignoreEmptyItem * @return {@link #getString(String[], String, boolean)} */ - public static String getString(String[] array, boolean ignoreEmptyItem) { + public static String getString(Object[] array, boolean ignoreEmptyItem) { return getString(array, null, ignoreEmptyItem); } /**获取string,为null则返回"" @@ -118,7 +117,7 @@ public static String getString(String[] array, boolean ignoreEmptyItem) { * @param split * @return {@link #getString(String[], String, boolean)} */ - public static String getString(String[] array, String split) { + public static String getString(Object[] array, String split) { return getString(array, split, false); } /**获取string,为null则返回"" @@ -127,7 +126,7 @@ public static String getString(String[] array, String split) { * @param ignoreEmptyItem * @return */ - public static String getString(String[] array, String split, boolean ignoreEmptyItem) { + public static String getString(Object[] array, String split, boolean ignoreEmptyItem) { String s = ""; if (array != null) { if (split == null) { @@ -304,43 +303,74 @@ public static boolean isNotEmpty(String s, boolean trim) { //判断字符类型 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< - public static final Pattern ALPHA_PATTERN; - public static final Pattern NAME_PATTERN; - public static final Pattern BIG_ALPHA_PATTERN; - public static final Pattern SMALL_ALPHA_PATTERN; + public static final Pattern PATTERN_NUMBER; + public static final Pattern PATTERN_PHONE; + public static final Pattern PATTERN_EMAIL; + public static final Pattern PATTERN_ID_CARD; + public static final Pattern PATTERN_ALPHA; + public static final Pattern PATTERN_PASSWORD; //TODO + public static final Pattern PATTERN_NAME; + public static final Pattern PATTERN_ALPHA_BIG; + public static final Pattern PATTERN_ALPHA_SMALL; static { - ALPHA_PATTERN = Pattern.compile("[a-zA-Z]"); - NAME_PATTERN = Pattern.compile("^[0-9a-zA-Z_]+$");//已用55个中英字符测试通过 - BIG_ALPHA_PATTERN = Pattern.compile("[A-Z]"); - SMALL_ALPHA_PATTERN = Pattern.compile("[a-z]"); - } - - //判断手机格式是否正确 + PATTERN_NUMBER = Pattern.compile("^[0-9]+$"); + PATTERN_ALPHA = Pattern.compile("^[a-zA-Z]+$"); + PATTERN_ALPHA_BIG = Pattern.compile("^[A-Z]+$"); + PATTERN_ALPHA_SMALL = Pattern.compile("^[a-z]+$"); + PATTERN_NAME = Pattern.compile("^[0-9a-zA-Z_]+$");//已用55个中英字符测试通过 + PATTERN_PHONE = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-2,5-9])|(17[0-9]))\\d{8}$"); + PATTERN_EMAIL = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"); + PATTERN_ID_CARD = Pattern.compile("(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}$)"); + PATTERN_PASSWORD = Pattern.compile("^[0-9a-zA-Z]+$"); + } + + /**判断手机格式是否正确 + * @param phone + * @return + */ public static boolean isPhone(String phone) { if (isNotEmpty(phone, true) == false) { return false; } - Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-2,5-9])|(17[0-9]))\\d{8}$"); - currentString = phone; - - return p.matcher(phone).matches(); + return PATTERN_PHONE.matcher(phone).matches(); + } + /**判断手机格式是否正确 + * @param s + * @return + */ + public static boolean isPassword(String s) { + return getLength(s, false) >= 6 && PATTERN_PASSWORD.matcher(s).matches(); } - //判断email格式是否正确 + /**判断是否全是数字密码 + * @param s + * @return + */ + public static boolean isNumberPassword(String s) { + return getLength(s, false) == 6 && isNumer(s); + } + /**判断email格式是否正确 + * @param email + * @return + */ public static boolean isEmail(String email) { if (isNotEmpty(email, true) == false) { return false; } - String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"; - Pattern p = Pattern.compile(str); - currentString = email; - - return p.matcher(email).matches(); + return PATTERN_EMAIL.matcher(email).matches(); } + + /**判断是否全是验证码 + * @param s + * @return + */ + public static boolean isVerify(String s) { + return getLength(s, false) >= 4 && isNumer(s); + } /**判断是否全是数字 * @param s * @return @@ -350,39 +380,20 @@ public static boolean isNumer(String s) { return false; } - Pattern pattern = Pattern.compile("[0-9]"); - Matcher matcher; - for (int i = 0; i < s.length(); i++) { - matcher = pattern.matcher(s.substring(i, i+1)); - if(! matcher.matches()){ - return false; - } - } - currentString = s; - - return true; + return PATTERN_NUMBER.matcher(s).matches(); } /**判断是否全是字母 * @param s * @return */ public static boolean isAlpha(String s) { - if (s == null) { - Log.i(TAG, "isNumberOrAlpha inputed == null >> return false;"); + if (isEmpty(s, true)) { return false; } - Pattern pAlpha = Pattern.compile("[a-zA-Z]"); - Matcher mAlpha; - for (int i = 0; i < s.length(); i++) { - mAlpha = pAlpha.matcher(s.substring(i, i+1)); - if(! mAlpha.matches()){ - return false; - } - } currentString = s; - return true; + return PATTERN_ALPHA.matcher(s).matches(); } /**判断是否全是数字或字母 * @param s @@ -392,53 +403,53 @@ public static boolean isNumberOrAlpha(String s) { return isNumer(s) || isAlpha(s); } - /**判断是否为单词,只能包含字母,数字或下划线 + /**判断是否为代码名称,只能包含字母,数字或下划线 * @param s * @return */ - public static boolean isWord(String s) { - return s != null && NAME_PATTERN.matcher(s).matches(); + public static boolean isName(String s) { + return s != null && PATTERN_NAME.matcher(s).matches(); } - /**判断是否为首字母大写的单词 + /**判断是否为首字母大写的代码名称 * @param key * @return */ - public static boolean isBigWord(String s) { + public static boolean isBigName(String s) { s = getString(s); - if (s.isEmpty() || BIG_ALPHA_PATTERN.matcher(s.substring(0, 1)).matches() == false) { + if (s.isEmpty() || PATTERN_ALPHA_BIG.matcher(s.substring(0, 1)).matches() == false) { return false; } - return s.length() <= 1 ? true : isWord(s.substring(1)); + return s.length() <= 1 ? true : isName(s.substring(1)); } - /**判断是否为首字母小写的单词 + /**判断是否为首字母小写的代码名称 * @param key * @return */ - public static boolean isSmallWord(String s) { + public static boolean isSmallName(String s) { s = getString(s); - if (s.isEmpty() || SMALL_ALPHA_PATTERN.matcher(s.substring(0, 1)).matches() == false) { + if (s.isEmpty() || PATTERN_ALPHA_SMALL.matcher(s.substring(0, 1)).matches() == false) { return false; } - return s.length() <= 1 ? true : isWord(s.substring(1)); + return s.length() <= 1 ? true : isName(s.substring(1)); } /**判断字符类型是否是身份证号 - * @param idCard + * @param number * @return */ - public static boolean isIDCard(String idCard) { - if (isNumberOrAlpha(idCard) == false) { + public static boolean isIDCard(String number) { + if (isNumberOrAlpha(number) == false) { return false; } - idCard = getString(idCard); - if (idCard.length() == 15) { - Log.i(TAG, "isIDCard idCard.length() == 15 old IDCard"); - currentString = idCard; + number = getString(number); + if (number.length() == 15) { + Log.i(TAG, "isIDCard number.length() == 15 old IDCard"); + currentString = number; return true; } - if (idCard.length() == 18) { - currentString = idCard; + if (number.length() == 18) { + currentString = number; return true; } diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/client/package-info.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/client/package-info.java deleted file mode 100644 index 84599fa4a..000000000 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/APIJSONLibrary/src/main/java/zuo/biao/apijson/client/package-info.java +++ /dev/null @@ -1,22 +0,0 @@ -/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License.*/ - -/** - * files for client projects - */ -/** - * @author Lemon - * - */ -package zuo.biao.apijson.client; \ No newline at end of file diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/HttpManager.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/HttpManager.java index 9bde4a758..e8c5d73c8 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/HttpManager.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/HttpManager.java @@ -14,12 +14,9 @@ package apijson.demo; -import static zuo.biao.apijson.StringUtil.UTF_8; - import java.io.IOException; import java.net.CookieHandler; import java.net.URI; -import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -87,58 +84,58 @@ public synchronized static HttpManager getInstance() { public static final String KEY_TOKEN = "token"; public static final String KEY_COOKIE = "cookie"; + // encode和decode太麻烦,直接都用HTTP POST + // /**GET请求 + // * @param paramList 请求参数列表,(可以一个键对应多个值) + // * @param url 接口url + // * @param requestCode + // * 请求码,类似onActivityResult中请求码,当同一activity中以实现接口方式发起多个网络请求时,请求结束后都会回调 + // * {@link OnHttpResponseListener#onHttpResponse(int, String, Exception)}
+ // * 在发起请求的类中可以用requestCode来区分各个请求 + // * @param listener + // */ + // public void get(final String url_, final String request, final OnHttpResponseListener listener) { + // Log.d(TAG, "get url_ = " + url_ + "; request = " + request + " >>>"); + // new AsyncTask() { + // + // String result; + // @Override + // protected Exception doInBackground(Void... params) { + // try { + // String url = StringUtil.getNoBlankString(url_) + // + URLEncoder.encode(StringUtil.getNoBlankString(request), UTF_8); + // StringBuffer sb = new StringBuffer(); + // sb.append(url); + // + // OkHttpClient client = getHttpClient(url); + // if (client == null) { + // return new Exception(TAG + ".get AsyncTask.doInBackground client == null >> return;"); + // } + // + // result = getResponseJson(client, new Request.Builder() + // .addHeader(KEY_TOKEN, getToken(url)) + // .url(sb.toString()).build()); + // } catch (Exception e) { + // Log.e(TAG, "get AsyncTask.doInBackground try { result = getResponseJson(..." + + // "} catch (Exception e) {\n" + e.getMessage()); + // return e; + // } + // + // return null; + // } + // + // @Override + // protected void onPostExecute(Exception exception) { + // super.onPostExecute(exception); + // listener.onHttpResponse(0, result, exception); + // } + // + // }.execute(); + // + // } + + public static final MediaType TYPE_JSON = MediaType.parse("application/json; charset=utf-8"); - /**GET请求 - * @param paramList 请求参数列表,(可以一个键对应多个值) - * @param url 接口url - * @param requestCode - * 请求码,类似onActivityResult中请求码,当同一activity中以实现接口方式发起多个网络请求时,请求结束后都会回调 - * {@link OnHttpResponseListener#onHttpResponse(int, String, Exception)}
- * 在发起请求的类中可以用requestCode来区分各个请求 - * @param listener - */ - public void get(final String url_, final String request, final OnHttpResponseListener listener) { - Log.d(TAG, "get url_ = " + url_ + "; request = " + request + " >>>"); - new AsyncTask() { - - String result; - @Override - protected Exception doInBackground(Void... params) { - try { - String url = StringUtil.getNoBlankString(url_) - + URLEncoder.encode(StringUtil.getNoBlankString(request), UTF_8); - StringBuffer sb = new StringBuffer(); - sb.append(url); - - OkHttpClient client = getHttpClient(url); - if (client == null) { - return new Exception(TAG + ".get AsyncTask.doInBackground client == null >> return;"); - } - - result = getResponseJson(client, new Request.Builder() - .addHeader(KEY_TOKEN, getToken(url)) - .url(sb.toString()).build()); - } catch (Exception e) { - Log.e(TAG, "get AsyncTask.doInBackground try { result = getResponseJson(..." + - "} catch (Exception e) {\n" + e.getMessage()); - return e; - } - - return null; - } - - @Override - protected void onPostExecute(Exception exception) { - super.onPostExecute(exception); - listener.onHttpResponse(0, result, exception); - } - - }.execute(); - - } - - public static final MediaType TYPE_JSON =MediaType.parse("application/json; charset=utf-8"); - /**POST请求 * @param paramList 请求参数列表,(可以一个键对应多个值) * @param url 接口url @@ -163,9 +160,9 @@ protected Exception doInBackground(Void... params) { if (client == null) { return new Exception(TAG + ".post AsyncTask.doInBackground client == null >> return;"); } - + RequestBody requestBody = RequestBody.create(TYPE_JSON, request); - + result = getResponseJson(client, new Request.Builder() .addHeader(KEY_TOKEN, getToken(url)).url(StringUtil.getNoBlankString(url)) .post(requestBody).build()); diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/RequestUtil.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/RequestUtil.java index a8e560f0b..b4cc06954 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/RequestUtil.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/RequestUtil.java @@ -23,11 +23,10 @@ import apijson.demo.application.DemoApplication; import apijson.demo.model.Comment; import apijson.demo.model.Moment; +import apijson.demo.model.Privacy; import apijson.demo.model.User; -import apijson.demo.model.Wallet; /**请求工具类 - * 设置encode参数只为方便展示,实际使用时并不需要 * @author Lemon */ public class RequestUtil { @@ -42,7 +41,7 @@ public class RequestUtil { - public static JSONObject newPostRequest(boolean encode) { + public static JSONObject newPostRequest() { Moment data = new Moment(); data.setUserId(DEFAULT_USER_ID); data.setContent(context.getString(R.string.apijson_slogan)); @@ -50,80 +49,76 @@ public static JSONObject newPostRequest(boolean encode) { list.add("http://static.oschina.net/uploads/user/1218/2437072_100.jpg?t=1461076033000"); list.add("http://common.cnblogs.com/images/icon_weibo_24.png"); data.setPictureList(list); - return new JSONRequest(data, encode).setTag(Moment.class.getSimpleName()); + return new JSONRequest(data).setTag(Moment.class.getSimpleName()); } - public static JSONObject newPutRequest(long id, boolean encode) { + public static JSONObject newPutRequest(long id) { Moment data = new Moment(id <= 0 ? DEFAULT_MOMENT_ID : id); // data.setContent(context.getString(R.string.apijson_info));//一般可用这种方式,encode是为了展示方便 List list = new ArrayList(); list.add((long) 82001); list.add((long) 82002); - JSONObject momentObject = new JSONObject(data, encode); - momentObject.put("praiseUserIdList+", list, encode); - momentObject.put("content", context.getString(R.string.apijson_info), encode); - return new JSONRequest(Moment.class.getSimpleName(), momentObject, encode).setTag(Moment.class.getSimpleName()); + JSONObject momentObject = new JSONObject(data); + momentObject.put("praiseUserIdList+", list); + momentObject.put("content", context.getString(R.string.apijson_info)); + return new JSONRequest(Moment.class.getSimpleName(), momentObject).setTag(Moment.class.getSimpleName()); } - public static JSONObject newDeleteRequest(long id, boolean encode) { - return new JSONRequest(new Moment(id <= 0 ? 10000 : id), encode).setTag(Moment.class.getSimpleName()); + public static JSONObject newDeleteRequest(long id) { + return new JSONRequest(new Moment(id <= 0 ? 10000 : id)).setTag(Moment.class.getSimpleName()); } - public static JSONObject newSingleRequest(long id, boolean encode) { - return new JSONRequest(new Moment(id <= 0 ? DEFAULT_MOMENT_ID : id), encode); + public static JSONObject newSingleRequest(long id) { + return new JSONRequest(new Moment(id <= 0 ? DEFAULT_MOMENT_ID : id)); } - public static JSONObject newColumnsRequest(long id, boolean encode) { - JSONObject object = new JSONObject(new Moment(id <= 0 ? DEFAULT_MOMENT_ID : id), encode); + public static JSONObject newColumnsRequest(long id) { + JSONObject object = new JSONObject(new Moment(id <= 0 ? DEFAULT_MOMENT_ID : id)); object.setColumn("id,userId,content"); - return new JSONRequest(Moment.class.getSimpleName(), object, encode); + return new JSONRequest(Moment.class.getSimpleName(), object); } - public static JSONObject newRelyRequest(long id, boolean encode) { + public static JSONObject newRelyRequest(long id) { JSONRequest request = new JSONRequest(); - request.put(new Moment(id <= 0 ? DEFAULT_MOMENT_ID : id), encode); - request.put(User.class.getSimpleName(), new JSONRequest("id@", "Moment/userId", encode)); + request.put(new Moment(id <= 0 ? DEFAULT_MOMENT_ID : id)); + request.put(User.class.getSimpleName(), new JSONRequest("id@", "Moment/userId")); return request; } - public static JSONObject newArrayRequest(boolean encode) { + public static JSONObject newArrayRequest() { JSONRequest dataObject = new JSONRequest(); - dataObject.put("name$", "%o%", encode); - JSONRequest request = new JSONRequest(User.class.getSimpleName(), dataObject, encode); - return request.toArray(5, 1, User.class.getSimpleName(), encode); + dataObject.put("name$", "%o%"); + JSONRequest request = new JSONRequest(User.class.getSimpleName(), dataObject); + return request.toArray(5, 1, User.class.getSimpleName()); } - public static JSONObject newComplexRequest(boolean encode) { + public static JSONObject newComplexRequest() { JSONRequest request = new JSONRequest(); List idList = new ArrayList(); idList.add(DEFAULT_USER_ID); idList.add((long) 93793); - request.put(Moment.class.getSimpleName(), new JSONRequest("userId{}", idList, encode), encode); + request.put(Moment.class.getSimpleName(), new JSONRequest("userId{}", idList)); - request.put(User.class.getSimpleName(), new JSONRequest("id@", "/Moment/userId", encode), encode); + request.put(User.class.getSimpleName(), new JSONRequest("id@", "/Moment/userId")); - request.add(new JSONRequest(Comment.class.getSimpleName() - , new JSONRequest("momentId@", "[]/Moment/id", encode), encode). - toArray(3, 0, Comment.class.getSimpleName()), encode); + request.putAll(new JSONRequest(Comment.class.getSimpleName() + , new JSONRequest("momentId@", "[]/Moment/id")). + toArray(3, 0, Comment.class.getSimpleName())); - return request.toArray(3, 0, encode); + return request.toArray(3, 0); } - public static JSONObject newAccessErrorRequest(boolean encode) { - return new JSONRequest(new Wallet().setUserId(DEFAULT_USER_ID), encode) - .setTag(Wallet.class.getSimpleName()); + public static JSONObject newAccessErrorRequest() { + return new JSONRequest(new Privacy(DEFAULT_USER_ID)); } - public static JSONObject newAccessPermittedRequest(boolean encode) { - JSONRequest request = new JSONRequest(); - request.put(new Wallet().setUserId(DEFAULT_USER_ID), encode); - request.put("currentUserId", DEFAULT_USER_ID, encode); - request.put("loginPassword", "apijson", encode); - return request.setTag(Wallet.class.getSimpleName()); + public static JSONObject newAccessPermittedRequest() { + JSONRequest request = new JSONRequest(new Privacy(DEFAULT_USER_ID)); + return request.setTag(Privacy.class.getSimpleName()); } } diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/model/Privacy.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/model/Privacy.java new file mode 100644 index 000000000..937621679 --- /dev/null +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/model/Privacy.java @@ -0,0 +1,98 @@ +/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License.*/ + +package apijson.demo.model; + +import static zuo.biao.apijson.RequestRole.ADMIN; +import static zuo.biao.apijson.RequestRole.OWNER; +import static zuo.biao.apijson.RequestRole.UNKNOWN; + +import zuo.biao.apijson.MethodAccess; + +/**用户隐私信息 + * @author Lemon + */ +@MethodAccess( + GET = {}, + POST_GET = {OWNER, ADMIN}, + POST = {UNKNOWN, ADMIN}, + DELETE = {ADMIN} + ) +public class Privacy extends BaseModel { + private static final long serialVersionUID = 1L; + + public static final int PASSWORD_TYPE_LOGIN = 0; + public static final int PASSWORD_TYPE_PAY = 1; + + private String phone; //手机 + private String password; //登录密码,隐藏字段 + private String payPassword; //支付密码,隐藏字段 + private Double balance; //余额 + + public Privacy() { + super(); + } + + public Privacy(long id) { + this(); + setId(id); + } + + public Privacy(String phone, String password) { + this(); + setPhone(phone); + setPassword(password); + } + + + + public String getPhone() { + return phone; + } + public Privacy setPhone(String phone) { + this.phone = phone; + return this; + } + + /**get_password会转为password + * @return + */ + public String get__password() { + return password; + } + public Privacy setPassword(String password) { + this.password = password; + return this; + } + + /**get_PayPassword会转为PayPassword + * @return + */ + public String get__payPassword() { + return payPassword; + } + public Privacy setPayPassword(String payPassword) { + this.payPassword = payPassword; + return this; + } + + public Double getBalance() { + return balance; + } + public Privacy setBalance(Double balance) { + this.balance = balance; + return this; + } + +} diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/model/Wallet.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/model/Wallet.java deleted file mode 100644 index 14ca08929..000000000 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/model/Wallet.java +++ /dev/null @@ -1,101 +0,0 @@ -/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License.*/ - -package apijson.demo.model; - -import static zuo.biao.apijson.RequestRole.ADMIN; -import static zuo.biao.apijson.RequestRole.OWNER; - -import java.math.BigDecimal; - -import zuo.biao.apijson.MethodAccess; - -/**钱包类,已用privacy替代 - * @author Lemon - * @see - *
POST_GET:
-{
-    "Wallet":{
-        "disallow":"!",
-        "necessary":"id"
-    }
-}
- * 
- *
POST:post/wallet
-{
-    "Wallet":{
-        "disallow":"!",
-        "necessary":"id"
-    },
-    "necessary":"payPassword"
-}
- * 
- *
PUT:put/wallet
-{
-    "Wallet":{
-        "disallow":"!",
-        "necessary":"id,balance+"
-    },
-    "necessary":"payPassword"
-}
- * 
- *
DELETE:delete/wallet
-{
-    "Wallet":{
-        "disallow":"!",
-        "necessary":"id"
-    },
-    "necessary":"payPassword"
-}
- * 
- */ -@Deprecated -@MethodAccess( - GET = {}, - HEAD = {}, - POST_GET = {OWNER, ADMIN}, - POST_HEAD = {OWNER, ADMIN}, - POST = {ADMIN}, - DELETE = {ADMIN} - ) -public class Wallet extends BaseModel { - private static final long serialVersionUID = 1L; - - public BigDecimal balance; - - /**默认构造方法,JSON等解析时必须要有 - */ - public Wallet() { - super(); - } - public Wallet(long id) { - this(); - setId(id); - } - - - public Wallet setUserId(long userId) { - setId(userId); - return this; - } - - public BigDecimal getBalance() { - return balance; - } - public Wallet setBalance(BigDecimal balance) { - this.balance = balance; - return this; - } - -} diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/AutoActivity.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/AutoActivity.java index 137cd4823..c067267c7 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/AutoActivity.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/AutoActivity.java @@ -131,7 +131,7 @@ public void request(TextView tv) { } public void request(String method) { startActivityForResult(RequestActivity.createIntent(context, id, url, method - , JSON.parseObject(StringUtil.getString(tvAutoRequest)), false), REQUEST_TO_REQUEST); + , JSON.parseObject(StringUtil.getString(tvAutoRequest))), REQUEST_TO_REQUEST); } diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/CodeUtil.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/CodeUtil.java index 007d6eac2..fc1b6d5d2 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/CodeUtil.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/CodeUtil.java @@ -43,14 +43,12 @@ public static String parse(final String name, final JSONObject request) { if (set != null) { Object value; - String pairKey; for (String key : set) { value = request.get(key); if (value == null) { continue; } - pairKey = new String(key instanceof String ? "\"" + key + "\"" : key); if (value instanceof JSONObject) {//APIJSON Array转为常规JSONArray if (isArrayKey(key)) {//APIJSON Array转为常规JSONArray response += NEWLINE + NEWLINE + "//" + key + "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"; @@ -65,22 +63,25 @@ public static String parse(final String name, final JSONObject request) { String prefix = key.substring(0, key.length() - 2); response += NEWLINE + NEWLINE - + parentKey + ".add(" + getItemKey(key) + ".toArray(" + + parentKey + ".putAll(" + getItemKey(key) + ".toArray(" + count + ", " + page + (prefix.isEmpty() ? "" : ", \"" + prefix + "\"") + "));"; response += NEWLINE + "//" + key + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + NEWLINE; - } else {//常规JSONObject,往下一级提取 + } + else {//常规JSONObject,往下一级提取 response += NEWLINE + NEWLINE + "//" + key + "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"; response += parse(key, (JSONObject) value); - response += NEWLINE + NEWLINE + parentKey + ".put(" + pairKey + ", " + getTableKey(key) + ");"; + response += NEWLINE + NEWLINE + parentKey + ".put(\"" + key + "\", " + getTableKey(key) + ");"; response += NEWLINE + "//" + key + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + NEWLINE; } - } else {//其它Object,直接填充 + } + else {//其它Object,直接填充 if (value instanceof String) { value = "\"" + value + "\""; - } else if (value instanceof JSONArray) { + } + else if (value instanceof JSONArray) { String s = StringUtil.getString(value); if (s.startsWith("[")) { s = s.substring(1); @@ -93,7 +94,7 @@ public static String parse(final String name, final JSONObject request) { value = "new Object[]{" + s + "}";//反射获取泛型太麻烦,反正开发中还要改的 } - response += NEWLINE + parentKey + ".put(" + pairKey + ", " + value + ");"; + response += NEWLINE + parentKey + ".put(\"" + key + "\", " + value + ");"; } } } diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/RequestActivity.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/RequestActivity.java index 82deb8b6a..e044c1f59 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/RequestActivity.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/RequestActivity.java @@ -14,6 +14,13 @@ package apijson.demo.ui; +import static zuo.biao.apijson.StringUtil.UTF_8; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; + +import zuo.biao.apijson.JSON; +import zuo.biao.apijson.JSONResponse; import android.app.Activity; import android.content.Context; import android.content.Intent; @@ -28,23 +35,15 @@ import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; - -import com.alibaba.fastjson.JSONObject; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; - import apijson.demo.HttpManager; import apijson.demo.HttpManager.OnHttpResponseListener; import apijson.demo.R; import apijson.demo.StringUtil; import apijson.demo.model.BaseModel; import apijson.demo.model.Moment; -import apijson.demo.model.Wallet; -import zuo.biao.apijson.JSON; -import zuo.biao.apijson.JSONResponse; +import apijson.demo.model.Privacy; -import static zuo.biao.apijson.StringUtil.UTF_8; +import com.alibaba.fastjson.JSONObject; /**请求Activity * 向服务器发起请求查询或操作相应数据 @@ -58,7 +57,6 @@ public class RequestActivity extends Activity implements OnHttpResponseListener public static final String INTENT_URL = "INTENT_URL"; public static final String INTENT_METHOD = "INTENT_METHOD"; public static final String INTENT_REQUEST = "INTENT_REQUEST"; - public static final String INTENT_ENCODED = "INTENT_ENCODED"; public static final String RESULT_ID = "RESULT_ID"; public static final String RESULT_URL = "RESULT_URL"; @@ -70,17 +68,14 @@ public class RequestActivity extends Activity implements OnHttpResponseListener * @param url * @param method * @param request - * @param encoded * @return */ - public static Intent createIntent(Context context, long id, String url, String method, - JSONObject request, boolean encoded) { + public static Intent createIntent(Context context, long id, String url, String method, JSONObject request) { return new Intent(context, RequestActivity.class) .putExtra(RequestActivity.INTENT_ID, id) .putExtra(RequestActivity.INTENT_URL, url) .putExtra(RequestActivity.INTENT_METHOD, method) - .putExtra(RequestActivity.INTENT_REQUEST, JSON.toJSONString(request)) - .putExtra(RequestActivity.INTENT_ENCODED, encoded); + .putExtra(RequestActivity.INTENT_REQUEST, JSON.toJSONString(request)); } @@ -91,10 +86,9 @@ public static Intent createIntent(Context context, long id, String url, String m private boolean isAlive; private long id; - private String url; - private String method; - private String request; - private boolean encoded; + private String url; + private String method; + private String request; private TextView tvRequestResult; private ProgressBar pbRequest; @@ -115,20 +109,9 @@ protected void onCreate(Bundle savedInstanceState) { url = getIntent().getStringExtra(INTENT_URL); method = getIntent().getStringExtra(INTENT_METHOD); request = getIntent().getStringExtra(INTENT_REQUEST); - encoded = getIntent().getBooleanExtra(INTENT_ENCODED, false); method = StringUtil.getTrimedString(method); url = StringUtil.getCorrectUrl(url); - if (encoded == false && request != null && request.contains("/")) { - // try {//导致JSON.format(request)返回null,然后tvRequestResult就显示为null了 - // String s = URLEncoder.encode(new String(request), StringUtil.UTF_8); - // request = s; - // } catch (UnsupportedEncodingException e) { - // e.printStackTrace(); - // } - request = request.replaceAll("/", "%2F"); - } - tvRequestResult = (TextView) findViewById(R.id.tvRequestResult); pbRequest = (ProgressBar) findViewById(R.id.pbRequest); @@ -176,11 +159,7 @@ private void request() { tvRequestResult.setText("requesting...\n\n url = " + fullUrl + "\n\n request = \n" + JSON.format(request) + "\n\n\n" + error); pbRequest.setVisibility(View.VISIBLE); - if ("get".equals(method) || "head".equals(method)) { - HttpManager.getInstance().get(fullUrl, request, this); - } else { - HttpManager.getInstance().post(fullUrl, request, this); - } + HttpManager.getInstance().post(fullUrl, request, this); } /**用浏览器请求,只有GET请求才能正常访问 @@ -244,15 +223,15 @@ public void onHttpResponse(int requestCode, final String resultJson, final Excep } else if ("delete".equals(method)) { response = response.getJSONResponse(Moment.class.getSimpleName()); - // if (JSONResponse.isSucceed(response)) {//delete succeed + // if (JSONResponse.isSuccess(response)) {//delete succeed id = 0;//reuse default value // } Log.d(TAG, "onHttpResponse delete.equals(method) >> id = " + id - + "; isSucceed = " + JSONResponse.isSucceed(response)); + + "; isSucceed = " + JSONResponse.isSuccess(response)); } else if ("post_get".equals(method)) { - Wallet wallet = response.getObject(Wallet.class); - Log.d(TAG, "onHttpResponse post_get.equals(method) >> wallet = " + JSON.toJSONString(wallet)); + Privacy privacy = response.getObject(Privacy.class); + Log.d(TAG, "onHttpResponse post_get.equals(method) >> privacy = \n" + JSON.toJSONString(privacy)); } diff --git a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/SelectActivity.java b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/SelectActivity.java index 0d716f4a8..928e00cb0 100644 --- a/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/SelectActivity.java +++ b/APIJSON-Android/APIJSON-AndroidStudio/APIJSONTest/app/src/main/java/apijson/demo/ui/SelectActivity.java @@ -109,7 +109,7 @@ public void toUpdateLog(View v) { */ public void setRequest() { for (int i = 0; i < buttons.length; i++) { - buttons[i].setText(JSON.format(getRequest(buttons[i], false))); + buttons[i].setText(JSON.format(getRequest(buttons[i]))); } } @@ -119,30 +119,30 @@ public void setRequest() { * @param v * @return */ - public JSONObject getRequest(View v, boolean encode) { + public JSONObject getRequest(View v) { switch (v.getId()) { case R.id.btnSelectPost: - return RequestUtil.newPostRequest(encode); + return RequestUtil.newPostRequest(); case R.id.btnSelectPut: - return RequestUtil.newPutRequest(id, encode); + return RequestUtil.newPutRequest(id); case R.id.btnSelectDelete: - return RequestUtil.newDeleteRequest(id, encode); + return RequestUtil.newDeleteRequest(id); case R.id.btnSelectSingle: - return RequestUtil.newSingleRequest(id, encode); + return RequestUtil.newSingleRequest(id); case R.id.btnSelectColumns: - return RequestUtil.newColumnsRequest(id, encode); + return RequestUtil.newColumnsRequest(id); case R.id.btnSelectRely: - return RequestUtil.newRelyRequest(id, encode); + return RequestUtil.newRelyRequest(id); case R.id.btnSelectArray: - return RequestUtil.newArrayRequest(encode); + return RequestUtil.newArrayRequest(); case R.id.btnSelectAccessError: - return RequestUtil.newAccessErrorRequest(encode); + return RequestUtil.newAccessErrorRequest(); case R.id.btnSelectAccessPermitted: - return RequestUtil.newAccessPermittedRequest(encode); + return RequestUtil.newAccessPermittedRequest(); default: - return RequestUtil.newComplexRequest(encode); + return RequestUtil.newComplexRequest(); } } @@ -153,31 +153,31 @@ public JSONObject getRequest(View v, boolean encode) { public void onClick(View v) { switch (v.getId()) { case R.id.btnSelectPost: - select(getRequest(v, true), "post"); + select(getRequest(v), "post"); break; case R.id.btnSelectPut: - select(getRequest(v, true), "put"); + select(getRequest(v), "put"); break; case R.id.btnSelectDelete: - select(getRequest(v, true), "delete"); + select(getRequest(v), "delete"); break; case R.id.btnSelectAccessError: - select(getRequest(v, true), "post_get"); + select(getRequest(v), "post_get"); break; case R.id.btnSelectAccessPermitted: - select(getRequest(v, true), "post_get"); + select(getRequest(v), "post_get"); break; default: - select(getRequest(v, true), "get"); + select(getRequest(v), "get"); break; } } private void select(JSONObject request, String method) { - startActivityForResult(RequestActivity.createIntent(context, id, url, method, request, true), REQUEST_TO_REQUEST); + startActivityForResult(RequestActivity.createIntent(context, id, url, method, request), REQUEST_TO_REQUEST); }