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());
}
相关文章
HttpClient的DnsResolver自定义DNS解析另一种选择深入研究
这篇文章主要为大家介绍了HttpClient的DnsResolver自定义DNS解析另一种选择深入研究,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-10-10SpringBoot整合mybatis/mybatis-plus实现数据持久化的操作
这篇文章主要介绍了SpringBoot整合mybatis/mybatis-plus实现数据持久化,本节内容我们介绍了数据持久化的相关操作,并且是基础传统的关系型数据库——mysql,需要的朋友可以参考下2022-10-10基于Spring Boot DevTools实现开发过程优化
这篇文章主要介绍了基于Spring Boot DevTools实现开发过程优化,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2020-09-09SpringBoot整合RabbitMQ及生产全场景高级特性实战
本文主要介绍了SpringBoot整合RabbitMQ及生产全场景高级特性实战,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2021-10-10
最新评论