fastjson-1.2.7.jar集成扩展,通用json文本解析源码

版权声明:本文为博主原创文章,博主允许自由转载。 https://blog.csdn.net/tx18/article/details/50432670
源文件webeasy/WEB-INF/classes/JSONEasy.java
package htok.apps;
import htok.Path;
import htok.tools.*;
import htok.we.html.*;
import htok.we.*;
import javax.servlet.http.*;
import java.util.*;
import com.alibaba.fastjson.*;

public class JSONEasy extends JspEasy
{
/*/构造对象
	public JSONEasy()
	{
		super();
	}*/
	public JSONEasy(HttpServletRequest request,HttpServletResponse response)
	{
		super(request,response);
	}
//解析JSON文本
	public void parseJson(String json)
	{parseJson(json,"j");}
	public void parseJson(String json,String prefix)
	{
		int pos = json.indexOf("[");
		if(pos==-1)
		{
			try {
				JSONObject jsonObj = JSON.parseObject(json);
				json2Bag(jsonObj,prefix,0);
			} catch (Exception e) {
				getBag("pPage").set("jsonerror", "Invalid JSON format");log(e.getMessage());
			}
		}
		else if(pos==0)
		{
			try {
				JSONArray jsonArr = JSON.parseArray(json);
				jsonArray2Bag(jsonArr,prefix,0);
			} catch (Exception e) {
				getBag("pPage").set("jsonerror", "Invalid JSON format");
			}
		}
		else{
			String str = json.substring(0,pos);
			str = str.trim();
			if(str.equals(""))
			{
				try {
					JSONArray jsonArr = JSON.parseArray(json);
					jsonArray2Bag(jsonArr,prefix,0);
				} catch (Exception e) {
					getBag("pPage").set("jsonerror", "Invalid JSON format");
				}
			}
			else{
				try {
					JSONObject jsonObj = JSON.parseObject(json);
					json2Bag(jsonObj,prefix,0);
				} catch (Exception e) {
					getBag("pPage").set("jsonerror", "Invalid JSON format");
				}
			}
		}
	}
	public void json2Bag(JSONObject jsonObj,String prefix,int level)
	{
		try {
			String key;
			String value;
			Bag b0 = new Bag(Bag.BAG);
			String prefix1;
			if(prefix.indexOf("0")>0)
				prefix1 = new StringBuffer(prefix).append(".").append(String.valueOf(level)).toString();
			else
				prefix1 = new StringBuffer(prefix).append(String.valueOf(level)).toString();
			setBag(prefix1,b0);//log(prefix1);
			int i=0;
			for (Map.Entry<String, Object> entry : jsonObj.entrySet())
			{
				key = entry.getKey();
				if(!tools.canName(key)) key = new StringBuffer("_").append(key).toString();
				Object ob = entry.getValue();
				if(ob instanceof JSONArray)//如果下级是json数组就调jsonArray2Bag
				{
					jsonArray2Bag((JSONArray)ob,prefix1,i);
					b0.set(key,new StringBuffer(prefix1).append(".").append(String.valueOf(i)).toString());
				}
				else if(ob instanceof JSONObject)//如果下级是json对象就递归
				{
					json2Bag((JSONObject)ob,prefix1,i);
					b0.set(key,new StringBuffer(prefix1).append(".").append(String.valueOf(i)).toString());
				}
				else{//如果下级是如果是文本或值,就放进书包
					value = String.valueOf(ob);
					if (!value.equals(""))
						b0.set(key, value);
				}
				i++;
			}
		} catch (Exception e) {
			getBag("pPage").set("jsonerror", "Invalid JSON format");
		}
	}
	public void jsonArray2Bag(JSONArray jsonArray,String prefix,int level)
	{
		try {
			Bag b0 = new Bag(Bag.BAG);
			String prefix1;
			if(prefix.indexOf("0")>0)
				prefix1 = new StringBuffer(prefix).append(".").append(String.valueOf(level)).toString();
			else
				prefix1 = new StringBuffer(prefix).append(String.valueOf(level)).toString();
			setBag(prefix1,b0);//log(prefix1);
			int i=0;
			for(Object ob :jsonArray)
			{
				b0.setSuffix(i);
				if(ob instanceof JSONArray)//如果下级是json数组就递归
				{
					jsonArray2Bag((JSONArray)ob,prefix1,i);
					b0.set("v",new StringBuffer(prefix1).append(".").append(String.valueOf(i)).toString());
				}
				else if(ob instanceof JSONObject)//如果下级是json对象就生成一个以对象名为id的书包
				{
					int j=0;
					for (Map.Entry<String, Object> entry : ((JSONObject)ob).entrySet())
					{
						String key = entry.getKey();
						if(!tools.canName(key)) key = new StringBuffer("_").append(key).toString();
						Object ob1 = entry.getValue();
						if(ob1 instanceof JSONArray)//如果下级是json数组就调jsonArray2Bag
						{
							jsonArray2Bag((JSONArray)ob1,new StringBuffer(prefix1).append(".").append(String.valueOf(i)).toString(),j);
							b0.set(key,new StringBuffer(prefix1).append(".").append(String.valueOf(i)).append(".").append(String.valueOf(j)).toString());
						}
						else if(ob1 instanceof JSONObject)//如果下级是json对象就递归
						{
							json2Bag((JSONObject)ob1,new StringBuffer(prefix1).append(".").append(String.valueOf(i)).toString(),j);
							b0.set(key,new StringBuffer(prefix1).append(".").append(String.valueOf(i)).append(".").append(String.valueOf(j)).toString());
						}
						else{//如果下级是如果是文本或值,就放进书包
							String value = String.valueOf(ob1);
							if (!value.equals(""))
								b0.set(key, value);
						}
						j++;
					}
					b0.set("v",new StringBuffer(prefix1).append(".").append(String.valueOf(i)).toString());
				}
				else{//如果下级是如果是文本或值,就放进书包
					String value = String.valueOf(ob);
					if (!value.equals(""))
						b0.set("v", value);
				}
				i++;
			}
		} catch (Exception e) {
			getBag("pPage").set("jsonerror", "Invalid JSON format");
		}
	}
	public void log(String str)
	{
		Path.log("JSONEasy_",str);
	}
}

下载:download.csdn.net/detail/tx18/9382604

帮忙扩展下一个通用JSON解析工具

08-22

现在只能针对下面这样的json和比它简单的json进行解析,能帮忙扩展一下么?rn[code=java]rnrn "name": "liuyx",rn "age": 23,rn "salary": 23.3,rn "lovers": [rn rn "name": "zhangweizhen",rn "age": 23rn ,rn rn "name": "zhaoushan",rn "age": 23rn ,rn rn "name": "huqiong",rn "age": 23rn rn ]rnrn[/code]rnrnJAVA代码:rnListsrnrn[code=java]rnpublic class Listsrnrn public static ArrayList newArrayList()rn rn return new ArrayList();rn rnrn[/code]rnrnStrings代码rn[code=java]rnpublic class Stringsrnrn public static boolean isNullOrEmpty(String s)rn rn return s == null || s.equals("");rn rnrn public static String nullToEmpty(String s)rn rn return s == null ? "" : s;rn rnrn /**rn * 将字符串首字母大写rn * @param srcrn * @returnrn */rn public static String capitalize(String src)rn rn if(src == null || src.equals("")) return src;rn char[] chars = src.toCharArray();rn final int len = chars.length;rn StringBuilder sb = new StringBuilder();rn for(int i = 0; i < len; i++)rn rn if(i == 0)rn rn char capChar = cap(chars[0]);rn sb.append(capChar);rn elsern sb.append(chars[i]);rn rn rnrn return sb.toString();rn rnrn /**rn * 从标准包名获得前缀rn * @param canonicalNamern * @returnrn */rn public static String getPrefixPackName(String canonicalName)rn String[] strs = canonicalName.split("[.]");rn int len = strs.length;rn StringBuilder sb = new StringBuilder();rn for(int i = 0; i < len - 1; i++)rn sb.append(strs[i]).append(".");rn rn sb.delete(sb.length()-1,sb.length());rn return sb.toString();rn rnrn private static char cap(char src)rn rn return (char)(src - 32);rn rnrn[/code]rnrnJSONParserUtil——通用JSON解析工具rn[code=java]rnpackage com.pplive.androidphone.ui.login.comment_system.utils;rnrnimport com.pplive.android.util.Lists;rnimport com.pplive.android.util.Strings;rnimport org.json.JSONArray;rnimport org.json.JSONException;rnimport org.json.JSONObject;rnrnimport java.lang.reflect.Field;rnimport java.lang.reflect.Method;rnimport java.util.Iterator;rnimport java.util.List;rnrn/**rn * User: youxueliurn * Date: 13-8-21rn * Time: 下午4:49rn */rnpublic class JSONParserUtil rnrn public static T parser(String json,Class cls)rn tryrn JSONObject jsonObject = new JSONObject(json);rn return parserJSONObj(jsonObject,cls);rn catch (JSONException e)rn // ignorern e.printStackTrace();rn rn return null;rn rnrn private static T parserJSONObj(JSONObject jsonObject,Class cls)rn tryrn T bean = cls.newInstance();rn final Iterator keys = jsonObject.keys();rn while(keys.hasNext())rn final String key = keys.next();rn final Object obj = jsonObject.opt(key);rn Field field = cls.getDeclaredField(key);rn final Class fieldType = field.getType();rn final String setMethodName = "set" + Strings.capitalize(key);rn final Method method = cls.getDeclaredMethod(setMethodName,fieldType);rn if(primitypeOrNull(obj))rn rn // 属性值默认全部认做Stringrn method.invoke(bean, obj + "");rn else if(obj instanceof JSONObject)rn method.invoke(bean, parserJSONObj((JSONObject) obj, fieldType));rn else if(obj instanceof JSONArray)rn final String nestClsName = cls.getCanonicalName()+"$"+Strings.capitalize(key.substring(0, key.length() - 1));rn final Class nestCls = Class.forName(nestClsName);rn final JSONArray jsonArray = (JSONArray)obj;rn method.invoke(bean, parserJSONArray(jsonArray, nestCls));rn rn rnrn return bean;rn catch (Exception e)rn // ignorern e.printStackTrace();rn rn return null;rn rnrn public static List parserJSONArray(JSONArray jsonArray,Class cls)rn final int len = jsonArray.length();rn List result = Lists.newArrayList();rn for(int i = 0; i < len; i++)rn final JSONObject jsonObject = jsonArray.optJSONObject(i);rn if(jsonObject != null)rn result.add(parserJSONObj(jsonObject,cls));rn elsern // 暂时还不知道怎么做rn rn rn return result;rn rnrnrn /**rn * 判断object是否是基本类型或者为nullrn * @param orn * @returnrn */rn private static boolean primitypeOrNull(Object o)rn return o == null || o instanceof Integer || o instanceof Long || o instanceof Float || o instanceof Double || o instanceof String;rn rnrnrnrnrn[/code]rnrn测试的Modelrn[code=java]rnpackage com.pplive.androidphone.ui.login.comment_system.model;rnrnimport java.util.List;rnrn/**rn * User: youxueliurn * Date: 13-8-22rn * Time: 上午10:27rn */rnpublic class Person rn private String name;rn private String salary;rn private String age;rnrn private List lovers;rnrn public List getLovers()rn return lovers;rn rnrn public void setLovers(List lovers)rn this.lovers = lovers;rn rnrn public static class Loverrn private String name;rn private String age;rnrn public String getName() rn return name;rn rnrn public void setName(String name) rn this.name = name;rn rnrn public String getAge() rn return age;rn rnrn public void setAge(String age) rn this.age = age;rn rn rnrn public void setName(String name)rn this.name = name;rn rnrn public void setSalary(String salary)rn this.salary = salary;rn rnrn public void setAge(String age)rn this.age = age;rn rnrn @Overridern public String toString() rn return "Person" +rn "name='" + name + '\'' +rn ", salary='" + salary + '\'' +rn ", age='" + age + '\'' +rn '';rn rnrnrn[/code]rnrn

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试