程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> java解析隨意率性層數json字符串的辦法

java解析隨意率性層數json字符串的辦法

編輯:關於JAVA

java解析隨意率性層數json字符串的辦法。本站提示廣大學習愛好者:(java解析隨意率性層數json字符串的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是java解析隨意率性層數json字符串的辦法正文



//解析戰略,有能夠是解析json字符串,有能夠為數據中的圖片地址,email等
package cc.util.regex;

public enum RegexPolicy {
 Json("Json"),
 Image("ImageFromHtml");

 private String value;
 RegexPolicy (String value) {
  this.value = value;
 }

 @Override
 public String toString() {
  // TODO Auto-generated method stub
  return value;
 }
}


package cc.util.regex;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;

/**
 * A static Class help to Analyze data
 * @author wangcccong
 * @version 1.140122
 * create at: 14-02-14
 */
public class RegexUtil {
 //與解析戰略相婚配的正則表達式
 //private static final String REGULAR_IMG_HTML = "<img +?src=\"(.+?)\"";
 private static final String REGULAR_JSON_ITEM_NAME = "\"([^\\\" ]+?)\":";
 //private static final String REGULAR_JSON_ARRAY_NAME = ", *?\" *?([a-zA-Z0-9]*?) *?\" *?: *?\\[ *?\\{";

        //公用辦法解析,將字符串傳入便可
 public static Object regex(final RegexPolicy policy, final String data) {
  switch (policy) {
  case Json:
   return regexJson(data);
  case Image:
   break;
  default:
   break;
  }
  return null;
 }

 /**
  *      By recursively parse the Json string, obtain the Json string name by the regular expression,
  * see also Matcher and Pattern and analysis of data. If the analytical data JsonObject object return key value pair (Map),
  *  if JsonArray List is returned, otherwise it returns String.
  *  <br><b>Notice:</b> if return Map you should better invoke map.get(null) to obtain value.
  * @see {@link java.util.regex.Matcher}, {@link java.util.regex.Pattern}
  * @param jsonStr
  * @return {@link java.util.Map} or {@link java.util.List} or {@link java.lang.String}
  */
 private static Object regexJson(final String jsonStr) {
  if (jsonStr == null) throw new NullPointerException("JsonString shouldn't be null");
  try {
   if (isJsonObject(jsonStr)) {
    final Pattern pattern = Pattern.compile(REGULAR_JSON_ITEM_NAME);
    final Matcher matcher = pattern.matcher(jsonStr);
    final Map<String, Object> map = new HashMap<String, Object>();
    final JSONObject jsonObject = new JSONObject(jsonStr);
    for ( ; matcher.find(); ) {
     String groupName = matcher.group(1);
     Object obj = jsonObject.opt(groupName);
     if (obj != null && isJsonArray(obj.toString()))
      matcher.region(matcher.end() + obj.toString().replace("\\", "").length(), matcher.regionEnd());
     if (obj != null && !map.containsKey(groupName))
      map.put(groupName, regexJson(obj.toString()));
    }
    return map;
   } else if (isJsonArray(jsonStr)) {
    List<Object> list = new ArrayList<Object>();
    JSONArray jsonArray = new JSONArray(jsonStr);
    for (int i = 0; i < jsonArray.length(); i++) {
     Object object = jsonArray.opt(i);
     list.add(regexJson(object.toString()));
    }
    return list;
   }
  } catch (Exception e) {
   // TODO: handle exception
   Log.e("RegexUtil--regexJson", e.getMessage()+"");
  }
  return jsonStr;
 }

 /**
  * To determine whether a string is JsonObject {@link org.json.JSONObject}
  * @param jsonStr {@link java.lang.String}
  * @return boolean
  */
 private static boolean isJsonObject(final String jsonStr) {
  if (jsonStr == null) return false;
  try {
   new JSONObject(jsonStr);
   return true;
  } catch (JSONException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return false;
  }
 }

 /**
  * To determine whether a string is JsonArray {@link org.json.JSONArray};
  * @param jsonStr {@link java.lang.String}
  * @return boolean
  */
 private static boolean isJsonArray(final String jsonStr) {
  if (jsonStr == null) return false;
  try {
   new JSONArray(jsonStr);
   return true;
  } catch (JSONException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return false;
  }
 }
}

//應用辦法
Object object = RegexUtil.regex(RegexPolicy.Json, jsonStr.substring(jsonStr.indexOf("{"),
         jsonStr.lastIndexOf("}")+1));
       if (object instanceof String) {
        Log.e("string", object.toString());
       } else if (object instanceof Map) {
        @SuppressWarnings("unchecked")
        HashMap<String, Object> map = (HashMap<String, Object>)object;
        Iterator<Entry<String, Object>>  iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
         Entry<String, Object> entry = iterator.next();
         if (entry.getValue() instanceof List) {
          Log.e(entry.getKey(), entry.getValue().toString());
         } else {
          Log.e(entry.getKey(), entry.getValue().toString());
         }
        }
       } else if (object instanceof List) {
        Log.e("list", object.toString());
       }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved