日期:2014-05-16  浏览次数:20294 次

读取JSON所有元素的属性和值

??? 有时候需要用JAVA将JSON字符串中的所有元系属性和值解析出来,例如:

String sql="[{\"typeNo\":\"PTMM01\",\"typeValue\":\"1\"},{\"typeNo\":\"PTMM02\",\"typeValue\":\"2\"}]";

?

你需要得到[typeNo:PTMM01, typeValue:1, typeNo:PTMM02, typeValue:2 ]这种属性和值对应的集合。

?

/**
	 * {读取JSON字符串的所有元素的属性和值,按此原理可以改造成功能更强大的JSON解析类}
	 * @author wenfeng.xu
	 * 
	 */
	public List convertJosnString(String str){
		List retVal=new ArrayList();
		String SYMBOL_OPEN_BRACE="{";
		String SYMBOL_CLOSE_BRACE="}";
		String SYMBOL_SINGLE_QUO_MARKS="\"";
		String SYMBOL_COLON=":";
		String SYMBOL_COMMA=",";
		String SYMBOL_OPEN_BRACKET="[";
		String SYMBOL_CLOSE_BRACKET="]";
		String PRE_SYMBOL_SINGLE_QUO_MARKS_0="PRE_SYMBOL_SINGLE_QUO_MARKS_0";//第一个单引号的索引
		String PRE_SYMBOL_SINGLE_QUO_MARKS_1="PRE_SYMBOL_SINGLE_QUO_MARKS_1";
		String PRE_SYMBOL_SINGLE_QUO_MARKS_2="PRE_SYMBOL_SINGLE_QUO_MARKS_2";
		String PRE_SYMBOL_SINGLE_QUO_MARKS_3="PRE_SYMBOL_SINGLE_QUO_MARKS_3";
		Map temMap=new HashMap();
		char[] temChar=str.toCharArray();
		for(int i=0;i<temChar.length;i++)
		{
			
			if(temMap.get(PRE_SYMBOL_SINGLE_QUO_MARKS_3)==null)
			{
			if(temChar[i]==SYMBOL_COLON.charAt(0))
			{
				temMap.put(SYMBOL_COLON,SYMBOL_COLON);
			}
			
			if(temChar[i]==SYMBOL_SINGLE_QUO_MARKS.charAt(0))
			{
				if(temMap.get(SYMBOL_SINGLE_QUO_MARKS)==null)
				{
					temMap.put(SYMBOL_SINGLE_QUO_MARKS,i);
				}else{//如果已经存在一个单引号
			        
			        if(temMap.get(SYMBOL_COLON)==null){//如果不存在冒号
			        	  temMap.put(PRE_SYMBOL_SINGLE_QUO_MARKS_0,Integer.parseInt(temMap.get(SYMBOL_SINGLE_QUO_MARKS).toString())+1);
					      temMap.put(PRE_SYMBOL_SINGLE_QUO_MARKS_1,i);
			        }else{
			      	      temMap.put(PRE_SYMBOL_SINGLE_QUO_MARKS_2,Integer.parseInt(temMap.get(SYMBOL_SINGLE_QUO_MARKS).toString())+1);
				          temMap.put(PRE_SYMBOL_SINGLE_QUO_MARKS_3,i);
		            }
			        temMap.remove(SYMBOL_SINGLE_QUO_MARKS);
			        
				}
			}
			}else{
				   int index_0=Integer.parseInt(temMap.get(PRE_SYMBOL_SINGLE_QUO_MARKS_0).toString());
				   int index_1=Integer.parseInt(temMap.get(PRE_SYMBOL_SINGLE_QUO_MARKS_1).toString()); 
				   int index_2=Integer.parseInt(temMap.get(PRE_SYMBOL_SINGLE_QUO_MARKS_2).toString()); 
				   int index_3=Integer.parseInt(temMap.get(PRE_SYMBOL_SINGLE_QUO_MARKS_3).toString());
				   String attr=str.substring(index_0,index_1);
				   String value=str.substring(index_2,index_3);
				   retVal.add(attr+":"+value);
				   temMap.remove(PRE_SYMBOL_SINGLE_QUO_MARKS_0);
				   temMap.remove(PRE_SYMBOL_SINGLE_QUO_MARKS_1);
				   temMap.remove(PRE_SYMBOL_SINGLE_QUO_MARKS_2);
				   temMap.remove(PRE_SYMBOL_SINGLE_QUO_MARKS_3);
				   temMap.remove(SYMBOL_COLON);
			}
		}
		
		return retVal;
	}

?

?

?