解析json字符串 java解析任意层数json字符串的方法
人气:0//解析策略,有可能是解析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());
}
加载全部内容