json类 方便调用
时间:2014-04-29 13:41:02
收藏:0
阅读:749
jsonutil类
1 package *********** 2 3 import java.lang.reflect.Field; 4 import java.lang.reflect.Type; 5 import java.util.ArrayList; 6 import java.util.HashMap; 7 import java.util.Iterator; 8 import java.util.List; 9 import java.util.Map; 10 11 import org.json.JSONArray; 12 import org.json.JSONException; 13 import org.json.JSONObject; 14 15 import android.util.Log; 16 17 public class JSONUtil { 18 public static boolean isPrintException = true; 19 private static String TAG = "JSONUtil"; 20 private static int modifierPSF = java.lang.reflect.Modifier.FINAL+java.lang.reflect.Modifier.STATIC+java.lang.reflect.Modifier.PUBLIC; 21 22 /** 23 * get Long from jsonObject 24 * 25 * @param jsonObject 26 * @param key 27 * @param defaultValue 28 * @return <ul> 29 * <li>if jsonObject is null, return defaultValue</li> 30 * <li>if key is null or empty, return defaultValue</li> 31 * <li>if {@link JSONObject#getLong(String)} exception, return 32 * defaultValue</li> 33 * <li>return {@link JSONObject#getLong(String)}</li> 34 * </ul> 35 */ 36 public static Long getLong(JSONObject jsonObject, String key, 37 Long defaultValue) { 38 if (jsonObject == null || StringUtil.isEmpty(key)) { 39 return defaultValue; 40 } 41 42 try { 43 return jsonObject.getLong(key); 44 } catch (JSONException e) { 45 if (isPrintException) { 46 e.printStackTrace(); 47 } 48 return defaultValue; 49 } 50 } 51 52 /** 53 * get Long from jsonData 54 * 55 * @param jsonData 56 * @param key 57 * @param defaultValue 58 * @return <ul> 59 * <li>if jsonObject is null, return defaultValue</li> 60 * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, 61 * return defaultValue</li> 62 * <li>return 63 * {@link JSONUtils#getLong(JSONObject, String, JSONObject)}</li> 64 * </ul> 65 */ 66 public static Long getLong(String jsonData, String key, Long defaultValue) { 67 if (StringUtil.isEmpty(jsonData)) { 68 return defaultValue; 69 } 70 71 try { 72 JSONObject jsonObject = new JSONObject(jsonData); 73 return getLong(jsonObject, key, defaultValue); 74 } catch (JSONException e) { 75 if (isPrintException) { 76 e.printStackTrace(); 77 } 78 return defaultValue; 79 } 80 } 81 82 /** 83 * @param jsonObject 84 * @param key 85 * @param defaultValue 86 * @return 87 * @see JSONUtils#getLong(JSONObject, String, Long) 88 */ 89 public static long getLong(JSONObject jsonObject, String key, 90 long defaultValue) { 91 return getLong(jsonObject, key, (Long) defaultValue); 92 } 93 94 /** 95 * @param jsonData 96 * @param key 97 * @param defaultValue 98 * @return 99 * @see JSONUtils#getLong(String, String, Long) 100 */ 101 public static long getLong(String jsonData, String key, long defaultValue) { 102 return getLong(jsonData, key, (Long) defaultValue); 103 } 104 105 /** 106 * get Int from jsonObject 107 * 108 * @param jsonObject 109 * @param key 110 * @param defaultValue 111 * @return <ul> 112 * <li>if jsonObject is null, return defaultValue</li> 113 * <li>if key is null or empty, return defaultValue</li> 114 * <li>if {@link JSONObject#getInt(String)} exception, return 115 * defaultValue</li> 116 * <li>return {@link JSONObject#getInt(String)}</li> 117 * </ul> 118 */ 119 public static Integer getInt(JSONObject jsonObject, String key, 120 Integer defaultValue) { 121 if (jsonObject == null || StringUtil.isEmpty(key)) { 122 return defaultValue; 123 } 124 125 try { 126 return jsonObject.getInt(key); 127 } catch (JSONException e) { 128 if (isPrintException) { 129 e.printStackTrace(); 130 } 131 return defaultValue; 132 } 133 } 134 135 /** 136 * get Int from jsonData 137 * 138 * @param jsonData 139 * @param key 140 * @param defaultValue 141 * @return <ul> 142 * <li>if jsonObject is null, return defaultValue</li> 143 * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, 144 * return defaultValue</li> 145 * <li>return 146 * {@link JSONUtils#getInt(JSONObject, String, JSONObject)}</li> 147 * </ul> 148 */ 149 public static Integer getInt(String jsonData, String key, 150 Integer defaultValue) { 151 if (StringUtil.isEmpty(jsonData)) { 152 return defaultValue; 153 } 154 155 try { 156 JSONObject jsonObject = new JSONObject(jsonData); 157 return getInt(jsonObject, key, defaultValue); 158 } catch (JSONException e) { 159 if (isPrintException) { 160 e.printStackTrace(); 161 } 162 return defaultValue; 163 } 164 } 165 166 /** 167 * @param jsonObject 168 * @param key 169 * @param defaultValue 170 * @return 171 * @see JSONUtils#getInt(JSONObject, String, Integer) 172 */ 173 public static int getInt(JSONObject jsonObject, String key, int defaultValue) { 174 return getInt(jsonObject, key, (Integer) defaultValue); 175 } 176 177 /** 178 * @param jsonObject 179 * @param key 180 * @param defaultValue 181 * @return 182 * @see JSONUtils#getInt(String, String, Integer) 183 */ 184 public static int getInt(String jsonData, String key, int defaultValue) { 185 return getInt(jsonData, key, (Integer) defaultValue); 186 } 187 188 /** 189 * get Double from jsonObject 190 * 191 * @param jsonObject 192 * @param key 193 * @param defaultValue 194 * @return <ul> 195 * <li>if jsonObject is null, return defaultValue</li> 196 * <li>if key is null or empty, return defaultValue</li> 197 * <li>if {@link JSONObject#getDouble(String)} exception, return 198 * defaultValue</li> 199 * <li>return {@link JSONObject#getDouble(String)}</li> 200 * </ul> 201 */ 202 public static Double getDouble(JSONObject jsonObject, String key, 203 Double defaultValue) { 204 if (jsonObject == null || StringUtil.isEmpty(key)) { 205 return defaultValue; 206 } 207 208 try { 209 return jsonObject.getDouble(key); 210 } catch (JSONException e) { 211 if (isPrintException) { 212 e.printStackTrace(); 213 } 214 return defaultValue; 215 } 216 } 217 218 /** 219 * get Double from jsonData 220 * 221 * @param jsonData 222 * @param key 223 * @param defaultValue 224 * @return <ul> 225 * <li>if jsonObject is null, return defaultValue</li> 226 * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, 227 * return defaultValue</li> 228 * <li>return 229 * {@link JSONUtils#getDouble(JSONObject, String, JSONObject)}</li> 230 * </ul> 231 */ 232 public static Double getDouble(String jsonData, String key, 233 Double defaultValue) { 234 if (StringUtil.isEmpty(jsonData)) { 235 return defaultValue; 236 } 237 238 try { 239 JSONObject jsonObject = new JSONObject(jsonData); 240 return getDouble(jsonObject, key, defaultValue); 241 } catch (JSONException e) { 242 if (isPrintException) { 243 e.printStackTrace(); 244 } 245 return defaultValue; 246 } 247 } 248 249 /** 250 * @param jsonObject 251 * @param key 252 * @param defaultValue 253 * @return 254 * @see JSONUtils#getDouble(JSONObject, String, Double) 255 */ 256 public static double getDouble(JSONObject jsonObject, String key, 257 double defaultValue) { 258 return getDouble(jsonObject, key, (Double) defaultValue); 259 } 260 261 /** 262 * @param jsonObject 263 * @param key 264 * @param defaultValue 265 * @return 266 * @see JSONUtils#getDouble(String, String, Double) 267 */ 268 public static double getDouble(String jsonData, String key, 269 double defaultValue) { 270 return getDouble(jsonData, key, (Double) defaultValue); 271 } 272 273 /** 274 * get String from jsonObject 275 * 276 * @param jsonObject 277 * @param key 278 * @param defaultValue 279 * @return <ul> 280 * <li>if jsonObject is null, return defaultValue</li> 281 * <li>if key is null or empty, return defaultValue</li> 282 * <li>if {@link JSONObject#getString(String)} exception, return 283 * defaultValue</li> 284 * <li>return {@link JSONObject#getString(String)}</li> 285 * </ul> 286 */ 287 public static String getString(JSONObject jsonObject, String key, 288 String defaultValue) { 289 if (jsonObject == null || StringUtil.isEmpty(key)) { 290 return defaultValue; 291 } 292 293 //这里使用optString是为了防止后台抛出异常 294 return jsonObject.optString(key); 295 } 296 297 /** 298 * get String from jsonData 299 * 300 * @param jsonData 301 * @param key 302 * @param defaultValue 303 * @return <ul> 304 * <li>if jsonObject is null, return defaultValue</li> 305 * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, 306 * return defaultValue</li> 307 * <li>return 308 * {@link JSONUtils#getString(JSONObject, String, JSONObject)}</li> 309 * </ul> 310 */ 311 public static String getString(String jsonData, String key, 312 String defaultValue) { 313 if (StringUtil.isEmpty(jsonData)) { 314 return defaultValue; 315 } 316 317 try { 318 JSONObject jsonObject = new JSONObject(jsonData); 319 return getString(jsonObject, key, defaultValue); 320 } catch (JSONException e) { 321 if (isPrintException) { 322 e.printStackTrace(); 323 } 324 return defaultValue; 325 } 326 } 327 328 /** 329 * get String array from jsonObject 330 * 331 * @param jsonObject 332 * @param key 333 * @param defaultValue 334 * @return <ul> 335 * <li>if jsonObject is null, return defaultValue</li> 336 * <li>if key is null or empty, return defaultValue</li> 337 * <li>if {@link JSONObject#getJSONArray(String)} exception, return 338 * defaultValue</li> 339 * <li>if {@link JSONArray#getString(int)} exception, return 340 * defaultValue</li> 341 * <li>return string array</li> 342 * </ul> 343 */ 344 public static String[] getStringArray(JSONObject jsonObject, String key, 345 String[] defaultValue) { 346 if (jsonObject == null || StringUtil.isEmpty(key)) { 347 return defaultValue; 348 } 349 350 try { 351 JSONArray statusArray = jsonObject.getJSONArray(key); 352 if (statusArray != null) { 353 String[] value = new String[statusArray.length()]; 354 for (int i = 0; i < statusArray.length(); i++) { 355 value[i] = statusArray.getString(i); 356 } 357 return value; 358 } 359 } catch (JSONException e) { 360 if (isPrintException) { 361 e.printStackTrace(); 362 } 363 return defaultValue; 364 } 365 return defaultValue; 366 } 367 368 /** 369 * get String array from jsonData 370 * 371 * @param jsonData 372 * @param key 373 * @param defaultValue 374 * @return <ul> 375 * <li>if jsonObject is null, return defaultValue</li> 376 * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, 377 * return defaultValue</li> 378 * <li>return 379 * {@link JSONUtils#getStringArray(JSONObject, String, JSONObject)}</li> 380 * </ul> 381 */ 382 public static String[] getStringArray(String jsonData, String key, 383 String[] defaultValue) { 384 if (StringUtil.isEmpty(jsonData)) { 385 return defaultValue; 386 } 387 388 try { 389 JSONObject jsonObject = new JSONObject(jsonData); 390 return getStringArray(jsonObject, key, defaultValue); 391 } catch (JSONException e) { 392 if (isPrintException) { 393 e.printStackTrace(); 394 } 395 return defaultValue; 396 } 397 } 398 399 /** 400 * get JSONObject from jsonObject 401 * 402 * @param jsonObject 403 * <em><em></em></em> 404 * @param key 405 * @param defaultValue 406 * @return <ul> 407 * <li>if jsonObject is null, return defaultValue</li> 408 * <li>if key is null or empty, return defaultValue</li> 409 * <li>if {@link JSONObject#getJSONObject(String)} exception, return 410 * defaultValue</li> 411 * <li>return {@link JSONObject#getJSONObject(String)}</li> 412 * </ul> 413 */ 414 public static JSONObject getJSONObject(JSONObject jsonObject, String key, 415 JSONObject defaultValue) { 416 if (jsonObject == null || StringUtil.isEmpty(key)) { 417 return defaultValue; 418 } 419 420 try { 421 return jsonObject.getJSONObject(key); 422 } catch (JSONException e) { 423 if (isPrintException) { 424 e.printStackTrace(); 425 } 426 return defaultValue; 427 } 428 } 429 430 /** 431 * get JSONObject from jsonData 432 * 433 * @param jsonData 434 * @param key 435 * @param defaultValue 436 * @return <ul> 437 * <li>if jsonObject is null, return defaultValue</li> 438 * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, 439 * return defaultValue</li> 440 * <li>return 441 * {@link JSONUtils#getJSONObject(JSONObject, String, JSONObject)}</li> 442 * </ul> 443 */ 444 public static JSONObject getJSONObject(String jsonData, String key, 445 JSONObject defaultValue) { 446 if (StringUtil.isEmpty(jsonData)) { 447 return defaultValue; 448 } 449 450 try { 451 JSONObject jsonObject = new JSONObject(jsonData); 452 return getJSONObject(jsonObject, key, defaultValue); 453 } catch (JSONException e) { 454 if (isPrintException) { 455 e.printStackTrace(); 456 } 457 return defaultValue; 458 } 459 } 460 461 /** 462 * get JSONArray from jsonObject 463 * 464 * @param jsonObject 465 * @param key 466 * @param defaultValue 467 * @return <ul> 468 * <li>if jsonObject is null, return defaultValue</li> 469 * <li>if key is null or empty, return defaultValue</li> 470 * <li>if {@link JSONObject#getJSONArray(String)} exception, return 471 * defaultValue</li> 472 * <li>return {@link JSONObject#getJSONArray(String)}</li> 473 * </ul> 474 */ 475 public static JSONArray getJSONArray(JSONObject jsonObject, String key, 476 JSONArray defaultValue) { 477 if (jsonObject == null || StringUtil.isEmpty(key)) { 478 return defaultValue; 479 } 480 481 try { 482 return jsonObject.getJSONArray(key); 483 } catch (JSONException e) { 484 if (isPrintException) { 485 e.printStackTrace(); 486 } 487 return defaultValue; 488 } 489 } 490 491 /** 492 * get JSONArray from jsonData 493 * 494 * @param jsonData 495 * @param key 496 * @param defaultValue 497 * @return <ul> 498 * <li>if jsonObject is null, return defaultValue</li> 499 * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, 500 * return defaultValue</li> 501 * <li>return 502 * {@link JSONUtils#getJSONArray(JSONObject, String, JSONObject)}</li> 503 * </ul> 504 */ 505 public static JSONArray getJSONArray(String jsonData, String key, 506 JSONArray defaultValue) { 507 if (StringUtil.isEmpty(jsonData)) { 508 return defaultValue; 509 } 510 511 try { 512 JSONObject jsonObject = new JSONObject(jsonData); 513 return getJSONArray(jsonObject, key, defaultValue); 514 } catch (JSONException e) { 515 if (isPrintException) { 516 e.printStackTrace(); 517 } 518 return defaultValue; 519 } 520 } 521 522 /** 523 * get Boolean from jsonObject 524 * 525 * @param jsonObject 526 * @param key 527 * @param defaultValue 528 * @return <ul> 529 * <li>if jsonObject is null, return defaultValue</li> 530 * <li>if key is null or empty, return defaultValue</li> 531 * <li>return {@link JSONObject#getBoolean(String)}</li> 532 * </ul> 533 */ 534 public static boolean getBoolean(JSONObject jsonObject, String key, 535 Boolean defaultValue) { 536 if (jsonObject == null || StringUtil.isEmpty(key)) { 537 return defaultValue; 538 } 539 540 try { 541 return jsonObject.getBoolean(key); 542 } catch (JSONException e) { 543 if (isPrintException) { 544 e.printStackTrace(); 545 } 546 return defaultValue; 547 } 548 } 549 550 /** 551 * get Boolean from jsonData 552 * 553 * @param jsonData 554 * @param key 555 * @param defaultValue 556 * @return <ul> 557 * <li>if jsonObject is null, return defaultValue</li> 558 * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, 559 * return defaultValue</li> 560 * <li>return 561 * {@link JSONUtils#getBoolean(JSONObject, String, Boolean)}</li> 562 * </ul> 563 */ 564 public static boolean getBoolean(String jsonData, String key, 565 Boolean defaultValue) { 566 if (StringUtil.isEmpty(jsonData)) { 567 return defaultValue; 568 } 569 570 try { 571 JSONObject jsonObject = new JSONObject(jsonData); 572 return getBoolean(jsonObject, key, defaultValue); 573 } catch (JSONException e) { 574 if (isPrintException) { 575 e.printStackTrace(); 576 } 577 return defaultValue; 578 } 579 } 580 581 /** 582 * get map from jsonObject. 583 * 584 * @param jsonObject 585 * key-value pairs json 586 * @param key 587 * @return <ul> 588 * <li>if jsonObject is null, return null</li> 589 * <li>return {@link JSONUtils#parseKeyAndValueToMap(String)}</li> 590 * </ul> 591 */ 592 public static Map<String, String> getMap(JSONObject jsonObject, String key) { 593 return JSONUtil.parseKeyAndValueToMap(JSONUtil.getString(jsonObject, 594 key, null)); 595 } 596 597 /** 598 * get map from jsonData. 599 * 600 * @param jsonData 601 * key-value pairs string 602 * @param key 603 * @return <ul> 604 * <li>if jsonData is null, return null</li> 605 * <li>if jsonData length is 0, return empty map</li> 606 * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, 607 * return null</li> 608 * <li>return {@link JSONUtils#getMap(JSONObject, String)}</li> 609 * </ul> 610 */ 611 public static Map<String, String> getMap(String jsonData, String key) { 612 613 if (jsonData == null) { 614 return null; 615 } 616 if (jsonData.length() == 0) { 617 return new HashMap<String, String>(); 618 } 619 620 try { 621 JSONObject jsonObject = new JSONObject(jsonData); 622 return getMap(jsonObject, key); 623 } catch (JSONException e) { 624 if (isPrintException) { 625 e.printStackTrace(); 626 } 627 return null; 628 } 629 } 630 631 /** 632 * parse key-value pairs to map. ignore empty key, if getValue exception, 633 * put empty value 634 * 635 * @param sourceObj 636 * key-value pairs json 637 * @return <ul> 638 * <li>if sourceObj is null, return null</li> 639 * <li>else parse entry by 640 * {@link MapUtils#putMapNotEmptyKey(Map, String, String)} one by 641 * one</li> 642 * </ul> 643 */ 644 @SuppressWarnings("rawtypes") 645 public static Map<String, String> parseKeyAndValueToMap(JSONObject sourceObj) { 646 if (sourceObj == null) { 647 return null; 648 } 649 650 Map<String, String> keyAndValueMap = new HashMap<String, String>(); 651 for (Iterator iter = sourceObj.keys(); iter.hasNext();) { 652 String key = (String) iter.next(); 653 MapUtil.putMapNotEmptyKey(keyAndValueMap, key, 654 getString(sourceObj, key, "")); 655 656 } 657 return keyAndValueMap; 658 } 659 660 /** 661 * parse key-value pairs to map. ignore empty key, if getValue exception, 662 * put empty value 663 * 664 * @param source 665 * key-value pairs json 666 * @return <ul> 667 * <li>if source is null or source‘s length is 0, return empty map</li> 668 * <li>if source {@link JSONObject#JSONObject(String)} exception, 669 * return null</li> 670 * <li>return {@link JSONUtils#parseKeyAndValueToMap(JSONObject)}</li> 671 * </ul> 672 */ 673 public static Map<String, String> parseKeyAndValueToMap(String source) { 674 if (StringUtil.isEmpty(source)) { 675 return null; 676 } 677 678 try { 679 JSONObject jsonObject = new JSONObject(source); 680 return parseKeyAndValueToMap(jsonObject); 681 } catch (JSONException e) { 682 if (isPrintException) { 683 e.printStackTrace(); 684 } 685 return null; 686 } 687 } 688 689 public Object getObject(JSONObject jsonObject, Class<?> c) throws Exception { 690 return getObject(jsonObject, c.getSimpleName(), c); 691 // return getObject(jsonObject, c.getSimpleName().toLowerCase(), c); 692 } 693 694 /** 695 * 从jsonObject中解析Key值,得到C对象 696 * 697 * @param jsonObject 698 * @param key 699 * query key 700 * @param c 701 * class 702 * @return object 703 * @throws Exception 704 */ 705 public static Object getObject(JSONObject jsonObject, String key, Class<?> c) throws Exception { 706 Log.v(TAG, "key == " + key); 707 Object bean = null; 708 if (jsonObject != null) { 709 JSONObject jo = null; 710 if (key != null) { 711 jo = jsonObject.getJSONObject(key); 712 } else { 713 jo = jsonObject; 714 } 715 if (jo != null) { 716 if (c.equals(null)) { 717 Log.v(TAG, "class is null"); 718 bean = jo.get(key); 719 } else { 720 bean = c.newInstance(); 721 // Field[] fs = c.getFields(); 722 Field[] fs = c.getDeclaredFields(); 723 for (int i = 0; i < fs.length; i++) { 724 Field f = fs[i]; 725 f.setAccessible(true); 726 Type type = f.getGenericType(); 727 if(f.getModifiers() == modifierPSF){//属性是final的,就不管 728 }else{ 729 String value = null; 730 //解析List 731 if(f.getType().equals(List.class)){ 732 String fClassName = toUpperCaseFirstOne(f.getName()); 733 String fClass = "com.startiaLime.shelf.info"+ fClassName; 734 f.set(bean,getList(jo.getJSONArray(fClassName), Class.forName(fClass))); 735 continue; 736 } 737 // value = jo.getString(f.getName()); 738 value = getString(jo, f.getName(), ""); 739 if(value.equals("")){ 740 //value是null 741 }else{ 742 Log.v(TAG, f.getName() + "=" + value); 743 if (type.equals(int.class)) { 744 if(value.length() == 0){ 745 f.setInt(bean, 0); 746 }else{ 747 f.setInt(bean, Integer.valueOf(value)); 748 } 749 } else if (type.equals(double.class)) { 750 if(value.length() == 0){ 751 f.setDouble(bean, 0); 752 }else{ 753 f.setDouble(bean, Double.valueOf(value)); 754 } 755 } else { 756 f.set(bean, value); 757 } 758 } 759 } 760 } 761 } 762 } else { 763 Log.v(TAG, "in jsonobject not key "); 764 } 765 } else { 766 Log.v(TAG, "current param jsonobject is null"); 767 } 768 return bean; 769 } 770 771 /** 772 *第一个字母转化成大写 773 * 774 */ 775 private static String toUpperCaseFirstOne(String s) { 776 if (Character.isUpperCase(s.charAt(0))) 777 return s; 778 else 779 return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString(); 780 } 781 782 /** 783 * 从jsonArray中解析得到List 784 * 785 * @param jsonArray 786 * @param key 787 * @param c 788 * @return 789 * @throws Exception 790 */ 791 public static List<Object> getList(JSONArray jsonArray, Class<?> c) 792 throws Exception { 793 List<Object> list = null; 794 795 if (!jsonArray.isNull(0)) { 796 list = new ArrayList<Object>(); 797 for (int i = 0; i < jsonArray.length(); i++) { 798 JSONObject jsObject = jsonArray.getJSONObject(i); 799 Object object = getObject(jsObject, null, c); 800 list.add(object); 801 } 802 }else if(jsonArray != null){ 803 return new ArrayList<Object>(); 804 } 805 return list; 806 } 807 808 /** 809 * 解析数组,返回一个链表 810 * 811 * @param key 812 * @param c 813 * List<E>, 814 * @return list 815 * @throws Exception 816 */ 817 public static List<Object> getList(JSONObject jsonObject,String key, Class<?> c) throws Exception { 818 if (jsonObject != null) { 819 JSONArray jsonArray = jsonObject.getJSONArray(key); 820 return getList(jsonArray, c); 821 } else { 822 return null; 823 } 824 } 825 826 }
package com.forfun.util; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class MapUtil { /** default separator between key and value **/ public static final String DEFAULT_KEY_AND_VALUE_SEPARATOR = ":"; /** default separator between key-value pairs **/ public static final String DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR = ","; /** * is null or its size is 0 * * <pre> * isEmpty(null) = true; * isEmpty({}) = true; * isEmpty({1, 2}) = false; * </pre> * * @param sourceMap * @return if map is null or its size is 0, return true, else return false. */ public static <K, V> boolean isEmpty(Map<K, V> sourceMap) { return (sourceMap == null || sourceMap.size() == 0); } /** * add key-value pair to map, and key need not null or empty * * @param map * @param key * @param value * @return <ul> * <li>if map is null, return false</li> * <li>if key is null or empty, return false</li> * <li>return {@link Map#put(Object, Object)}</li> * </ul> */ public static boolean putMapNotEmptyKey(Map<String, String> map, String key, String value) { if (map == null || StringUtil.isEmpty(key)) { return false; } map.put(key, value); return true; } /** * add key-value pair to map, both key and value need not null or empty * * @param map * @param key * @param value * @return <ul> * <li>if map is null, return false</li> * <li>if key is null or empty, return false</li> * <li>if value is null or empty, return false</li> * <li>return {@link Map#put(Object, Object)}</li> * </ul> */ public static boolean putMapNotEmptyKeyAndValue(Map<String, String> map, String key, String value) { if (map == null || StringUtil.isEmpty(key) || StringUtil.isEmpty(value)) { return false; } map.put(key, value); return true; } /** * add key-value pair to map, key need not null or empty * * @param map * @param key * @param value * @param defaultValue * @return <ul> * <li>if map is null, return false</li> * <li>if key is null or empty, return false</li> * <li>if value is null or empty, put defaultValue, return true</li> * <li>if value is neither null nor empty,put value, return true</li> * </ul> */ public static boolean putMapNotEmptyKeyAndValue(Map<String, String> map, String key, String value, String defaultValue) { if (map == null || StringUtil.isEmpty(key)) { return false; } map.put(key, StringUtil.isEmpty(value) ? defaultValue : value); return true; } /** * add key-value pair to map, key need not null * * @param map * @param key * @param value * @return <ul> * <li>if map is null, return false</li> * <li>if key is null, return false</li> * <li>return {@link Map#put(Object, Object)}</li> * </ul> */ public static <K, V> boolean putMapNotNullKey(Map<K, V> map, K key, V value) { if (map == null || key == null) { return false; } map.put(key, value); return true; } /** * add key-value pair to map, both key and value need not null * * @param map * @param key * @param value * @return <ul> * <li>if map is null, return false</li> * <li>if key is null, return false</li> * <li>if value is null, return false</li> * <li>return {@link Map#put(Object, Object)}</li> * </ul> */ public static <K, V> boolean putMapNotNullKeyAndValue(Map<K, V> map, K key, V value) { if (map == null || key == null || value == null) { return false; } map.put(key, value); return true; } /** * get key by value, match the first entry front to back * <ul> * <strong>Attentions:</strong> * <li>for HashMap, the order of entry not same to put order, so you may * need to use TreeMap</li> * </ul> * * @param <V> * @param map * @param value * @return <ul> * <li>if map is null, return null</li> * <li>if value exist, return key</li> * <li>return null</li> * </ul> */ public static <K, V> K getKeyByValue(Map<K, V> map, V value) { if (isEmpty(map)) { return null; } for (Entry<K, V> entry : map.entrySet()) { if (ObjectUtil.isEquals(entry.getValue(), value)) { return entry.getKey(); } } return null; } /** * parse key-value pairs to map, ignore empty key * * <pre> * parseKeyAndValueToMap("","","",true)=null * parseKeyAndValueToMap(null,"","",true)=null * parseKeyAndValueToMap("a:b,:","","",true)={(a,b)} * parseKeyAndValueToMap("a:b,:d","","",true)={(a,b)} * parseKeyAndValueToMap("a:b,c:d","","",true)={(a,b),(c,d)} * parseKeyAndValueToMap("a=b, c = d","=",",",true)={(a,b),(c,d)} * parseKeyAndValueToMap("a=b, c = d","=",",",false)={(a, b),( c , d)} * parseKeyAndValueToMap("a=b, c=d","=", ",", false)={(a,b),( c,d)} * parseKeyAndValueToMap("a=b; c=d","=", ";", false)={(a,b),( c,d)} * parseKeyAndValueToMap("a=b, c=d", ",", ";", false)={(a=b, c=d)} * </pre> * * @param source * key-value pairs * @param keyAndValueSeparator * separator between key and value * @param keyAndValuePairSeparator * separator between key-value pairs * @param ignoreSpace * whether ignore space at the begging or end of key and value * @return */ public static Map<String, String> parseKeyAndValueToMap(String source, String keyAndValueSeparator, String keyAndValuePairSeparator, boolean ignoreSpace) { if (StringUtil.isEmpty(source)) { return null; } if (StringUtil.isEmpty(keyAndValueSeparator)) { keyAndValueSeparator = DEFAULT_KEY_AND_VALUE_SEPARATOR; } if (StringUtil.isEmpty(keyAndValuePairSeparator)) { keyAndValuePairSeparator = DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR; } Map<String, String> keyAndValueMap = new HashMap<String, String>(); String[] keyAndValueArray = source.split(keyAndValuePairSeparator); if (keyAndValueArray == null) { return null; } int seperator; for (String valueEntity : keyAndValueArray) { if (!StringUtil.isEmpty(valueEntity)) { seperator = valueEntity.indexOf(keyAndValueSeparator); if (seperator != -1) { if (ignoreSpace) { MapUtil.putMapNotEmptyKey(keyAndValueMap, valueEntity .substring(0, seperator).trim(), valueEntity .substring(seperator + 1).trim()); } else { MapUtil.putMapNotEmptyKey(keyAndValueMap, valueEntity.substring(0, seperator), valueEntity.substring(seperator + 1)); } } } } return keyAndValueMap; } /** * parse key-value pairs to map, ignore empty key * * @param source * key-value pairs * @param ignoreSpace * whether ignore space at the begging or end of key and value * @return * @see {@link MapUtil#parseKeyAndValueToMap(String, String, String, boolean)} * , keyAndValueSeparator is {@link #DEFAULT_KEY_AND_VALUE_SEPARATOR}, * keyAndValuePairSeparator is * {@link #DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR} */ public static Map<String, String> parseKeyAndValueToMap(String source, boolean ignoreSpace) { return parseKeyAndValueToMap(source, DEFAULT_KEY_AND_VALUE_SEPARATOR, DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR, ignoreSpace); } /** * parse key-value pairs to map, ignore empty key, ignore space at the * begging or end of key and value * * @param source * key-value pairs * @return * @see {@link MapUtil#parseKeyAndValueToMap(String, String, String, boolean)} * , keyAndValueSeparator is {@link #DEFAULT_KEY_AND_VALUE_SEPARATOR}, * keyAndValuePairSeparator is * {@link #DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR}, ignoreSpace is true */ public static Map<String, String> parseKeyAndValueToMap(String source) { return parseKeyAndValueToMap(source, DEFAULT_KEY_AND_VALUE_SEPARATOR, DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR, true); } /** * join map * * @param map * @return */ public static String toJson(Map<String, String> map) { if (map == null || map.size() == 0) { return null; } StringBuilder paras = new StringBuilder(); paras.append("{"); Iterator<Map.Entry<String, String>> ite = map.entrySet().iterator(); while (ite.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) ite .next(); paras.append("\"").append(entry.getKey()).append("\":\"") .append(entry.getValue()).append("\""); if (ite.hasNext()) { paras.append(","); } } paras.append("}"); return paras.toString(); } }
1 package com.forfun.util; 2 3 public class ObjectUtil { 4 /** 5 * compare two object 6 * 7 * @param actual 8 * @param expected 9 * @return <ul> 10 * <li>if both are null, return true</li> 11 * <li>return actual.{@link Object#equals(Object)}</li> 12 * </ul> 13 */ 14 public static boolean isEquals(Object actual, Object expected) { 15 return actual == expected 16 || (actual == null ? expected == null : actual.equals(expected)); 17 } 18 19 /** 20 * convert long array to Long array 21 * 22 * @param source 23 * @return 24 */ 25 public static Long[] transformLongArray(long[] source) { 26 Long[] destin = new Long[source.length]; 27 for (int i = 0; i < source.length; i++) { 28 destin[i] = source[i]; 29 } 30 return destin; 31 } 32 33 /** 34 * convert Long array to long array 35 * 36 * @param source 37 * @return 38 */ 39 public static long[] transformLongArray(Long[] source) { 40 long[] destin = new long[source.length]; 41 for (int i = 0; i < source.length; i++) { 42 destin[i] = source[i]; 43 } 44 return destin; 45 } 46 47 /** 48 * convert int array to Integer array 49 * 50 * @param source 51 * @return 52 */ 53 public static Integer[] transformIntArray(int[] source) { 54 Integer[] destin = new Integer[source.length]; 55 for (int i = 0; i < source.length; i++) { 56 destin[i] = source[i]; 57 } 58 return destin; 59 } 60 61 /** 62 * convert Integer array to int array 63 * 64 * @param source 65 * @return 66 */ 67 public static int[] transformIntArray(Integer[] source) { 68 int[] destin = new int[source.length]; 69 for (int i = 0; i < source.length; i++) { 70 destin[i] = source[i]; 71 } 72 return destin; 73 } 74 75 /** 76 * compare two object 77 * <ul> 78 * <strong>About result</strong> 79 * <li>if v1 > v2, return 1</li> 80 * <li>if v1 = v2, return 0</li> 81 * <li>if v1 < v2, return -1</li> 82 * </ul> 83 * <ul> 84 * <strong>About rule</strong> 85 * <li>if v1 is null, v2 is null, then return 0</li> 86 * <li>if v1 is null, v2 is not null, then return -1</li> 87 * <li>if v1 is not null, v2 is null, then return 1</li> 88 * <li>return v1.{@link Comparable#compareTo(Object)}</li> 89 * </ul> 90 * 91 * @param v1 92 * @param v2 93 * @return 94 */ 95 @SuppressWarnings({ "unchecked", "rawtypes" }) 96 public static <V> int compare(V v1, V v2) { 97 return v1 == null ? (v2 == null ? 0 : -1) : (v2 == null ? 1 98 : ((Comparable) v1).compareTo(v2)); 99 } 100 }
package com.forfun.util; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringUtil { /** * is null or its length is 0 or it is made by space * * <pre> * isBlank(null) = true; * isBlank("") = true; * isBlank(" ") = true; * isBlank("a") = false; * isBlank("a ") = false; * isBlank(" a") = false; * isBlank("a b") = false; * </pre> * * @param str * @return if string is null or its size is 0 or it is made by space, return * true, else return false. */ public static boolean isBlank(String str) { return (str == null || str.trim().length() == 0); } /** * is null or its length is 0 * * <pre> * isEmpty(null) = true; * isEmpty("") = true; * isEmpty(" ") = false; * </pre> * * @param str * @return if string is null or its size is 0, return true, else return * false. */ public static boolean isEmpty(String str) { return (str == null || str.length() == 0); } /** * compare two string * * @param actual * @param expected * @return * @see ObjectUtils#isEquals(Object, Object) */ public static boolean isEquals(String actual, String expected) { return ObjectUtil.isEquals(actual, expected); } /** * null string to empty string * * <pre> * nullStrToEmpty(null) = ""; * nullStrToEmpty("") = ""; * nullStrToEmpty("aa") = "aa"; * </pre> * * @param str * @return */ public static String nullStrToEmpty(String str) { return (str == null ? "" : str); } /** * capitalize first letter * * <pre> * capitalizeFirstLetter(null) = null; * capitalizeFirstLetter("") = ""; * capitalizeFirstLetter("2ab") = "2ab" * capitalizeFirstLetter("a") = "A" * capitalizeFirstLetter("ab") = "Ab" * capitalizeFirstLetter("Abc") = "Abc" * </pre> * * @param str * @return */ public static String capitalizeFirstLetter(String str) { if (isEmpty(str)) { return str; } char c = str.charAt(0); return (!Character.isLetter(c) || Character.isUpperCase(c)) ? str : new StringBuilder(str.length()) .append(Character.toUpperCase(c)) .append(str.substring(1)).toString(); } /** * encoded in utf-8 * * <pre> * utf8Encode(null) = null * utf8Encode("") = ""; * utf8Encode("aa") = "aa"; * utf8Encode("啊啊啊啊") = "%E5%95%8A%E5%95%8A%E5%95%8A%E5%95%8A"; * </pre> * * @param str * @return * @throws UnsupportedEncodingException * if an error occurs */ public static String utf8Encode(String str) { if (!isEmpty(str) && str.getBytes().length != str.length()) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException( "UnsupportedEncodingException occurred. ", e); } } return str; } /** * encoded in utf-8, if exception, return defultReturn * * @param str * @param defultReturn * @return */ public static String utf8Encode(String str, String defultReturn) { if (!isEmpty(str) && str.getBytes().length != str.length()) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { return defultReturn; } } return str; } /** * get innerHtml from href * * <pre> * getHrefInnerHtml(null) = "" * getHrefInnerHtml("") = "" * getHrefInnerHtml("mp3") = "mp3"; * getHrefInnerHtml("<a innerHtml</a>") = "<a innerHtml</a>"; * getHrefInnerHtml("<a>innerHtml</a>") = "innerHtml"; * getHrefInnerHtml("<a<a>innerHtml</a>") = "innerHtml"; * getHrefInnerHtml("<a href="baidu.com">innerHtml</a>") = "innerHtml"; * getHrefInnerHtml("<a href="baidu.com" title="baidu">innerHtml</a>") = "innerHtml"; * getHrefInnerHtml(" <a>innerHtml</a> ") = "innerHtml"; * getHrefInnerHtml("<a>innerHtml</a></a>") = "innerHtml"; * getHrefInnerHtml("jack<a>innerHtml</a></a>") = "innerHtml"; * getHrefInnerHtml("<a>innerHtml1</a><a>innerHtml2</a>") = "innerHtml2"; * </pre> * * @param href * @return <ul> * <li>if href is null, return ""</li> * <li>if not match regx, return source</li> * <li>return the last string that match regx</li> * </ul> */ public static String getHrefInnerHtml(String href) { if (isEmpty(href)) { return ""; } String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*"; Pattern hrefPattern = Pattern .compile(hrefReg, Pattern.CASE_INSENSITIVE); Matcher hrefMatcher = hrefPattern.matcher(href); if (hrefMatcher.matches()) { return hrefMatcher.group(1); } return href; } /** * process special char in html * * <pre> * htmlEscapeCharsToString(null) = null; * htmlEscapeCharsToString("") = ""; * htmlEscapeCharsToString("mp3") = "mp3"; * htmlEscapeCharsToString("mp3<") = "mp3<"; * htmlEscapeCharsToString("mp3>") = "mp3\>"; * htmlEscapeCharsToString("mp3&mp4") = "mp3&mp4"; * htmlEscapeCharsToString("mp3"mp4") = "mp3\"mp4"; * htmlEscapeCharsToString("mp3<>&"mp4") = "mp3\<\>&\"mp4"; * </pre> * * @param source * @return */ public static String htmlEscapeCharsToString(String source) { return StringUtil.isEmpty(source) ? source : source .replaceAll("<", "<").replaceAll(">", ">") .replaceAll("&", "&").replaceAll(""", "\""); } /** * transform half width char to full width char * * <pre> * fullWidthToHalfWidth(null) = null; * fullWidthToHalfWidth("") = ""; * fullWidthToHalfWidth(new String(new char[] {12288})) = " "; * fullWidthToHalfWidth("!"#$%&) = "!\"#$%&"; * </pre> * * @param s * @return */ public static String fullWidthToHalfWidth(String s) { if (isEmpty(s)) { return s; } char[] source = s.toCharArray(); for (int i = 0; i < source.length; i++) { if (source[i] == 12288) { source[i] = ‘ ‘; // } else if (source[i] == 12290) { // source[i] = ‘.‘; } else if (source[i] >= 65281 && source[i] <= 65374) { source[i] = (char) (source[i] - 65248); } else { source[i] = source[i]; } } return new String(source); } /** * transform full width char to half width char * * <pre> * halfWidthToFullWidth(null) = null; * halfWidthToFullWidth("") = ""; * halfWidthToFullWidth(" ") = new String(new char[] {12288}); * halfWidthToFullWidth("!\"#$%&) = "!"#$%&"; * </pre> * * @param s * @return */ public static String halfWidthToFullWidth(String s) { if (isEmpty(s)) { return s; } char[] source = s.toCharArray(); for (int i = 0; i < source.length; i++) { if (source[i] == ‘ ‘) { source[i] = (char) 12288; // } else if (source[i] == ‘.‘) { // source[i] = (char)12290; } else if (source[i] >= 33 && source[i] <= 126) { source[i] = (char) (source[i] + 65248); } else { source[i] = source[i]; } } return new String(source); } }
评论(0)