将JAVA对象转换成JSON字符串

package com.jetsum.util;

import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import antlr.RecognitionException;
import antlr.TokenStreamException;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.model.JSONArray;
import com.sdicons.json.model.JSONValue;
import com.sdicons.json.parser.JSONParser;

public class JsonUtil {

	/**
	 * JAVA对象转换成JSON字符串
	 * @param obj
	 * @return
	 * @throws MapperException
	 */	
	public static String objectToJsonStr(Object obj) throws MapperException{
        JSONValue jsonValue = JSONMapper.toJSON(obj);  
        String jsonStr = jsonValue.render(false);
        return jsonStr;
	}
	
	/**
	 * 重载objectToJsonStr方法
	 * @param obj 需要转换的JAVA对象
	 * @param format 是否格式化
	 * @return
	 * @throws MapperException
	 */
	public static String objectToJsonStr(Object obj,boolean format) throws MapperException{
        JSONValue jsonValue = JSONMapper.toJSON(obj);  
        String jsonStr = jsonValue.render(format);
        return jsonStr;
	}	
	
	/**
	 * JSON字符串转换成JAVA对象
	 * @param jsonStr
	 * @param cla
	 * @return
	 * @throws MapperException
	 * @throws TokenStreamException
	 * @throws RecognitionException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object jsonStrToObject(String jsonStr,Class<?> cla) throws MapperException, TokenStreamException, RecognitionException{
		Object obj = null;
		try{
	        JSONParser parser = new JSONParser(new StringReader(jsonStr));    
	        JSONValue jsonValue = parser.nextValue();  	        
	        if(jsonValue instanceof com.sdicons.json.model.JSONArray){
	        	List list = new ArrayList();
	        	JSONArray jsonArray = (JSONArray) jsonValue;
	        	for(int i=0;i<jsonArray.size();i++){
	        		JSONValue jsonObj = jsonArray.get(i);
	        		Object javaObj = JSONMapper.toJava(jsonObj,cla); 
	        		list.add(javaObj);
	        	}
	        	obj = list;
	        }else if(jsonValue instanceof com.sdicons.json.model.JSONObject){
	        	obj = JSONMapper.toJava(jsonValue,cla); 
	        }else{
	        	obj = jsonValue;
	        }
        }catch(Exception e){
        	e.printStackTrace();
        }
        return obj; 
	}
	
	/**
	 * 将JAVA对象转换成JSON字符串
	 * @param obj
	 * @return
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	@SuppressWarnings("rawtypes")
	public static String simpleObjectToJsonStr(Object obj,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{
		if(obj==null){
			return "null";
		}
		String jsonStr = "{";
		Class<?> cla = obj.getClass();
		Field fields[] = cla.getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			if(field.getType() == long.class){
				jsonStr += "\""+field.getName()+"\":"+field.getLong(obj)+",";
			}else if(field.getType() == double.class){
				jsonStr += "\""+field.getName()+"\":"+field.getDouble(obj)+",";
			}else if(field.getType() == float.class){
				jsonStr += "\""+field.getName()+"\":"+field.getFloat(obj)+",";
			}else if(field.getType() == int.class){
				jsonStr += "\""+field.getName()+"\":"+field.getInt(obj)+",";
			}else if(field.getType() == boolean.class){
				jsonStr += "\""+field.getName()+"\":"+field.getBoolean(obj)+",";
			}else if(field.getType() == Integer.class||field.getType() == Boolean.class
					||field.getType() == Double.class||field.getType() == Float.class					
					||field.getType() == Long.class){				
				jsonStr += "\""+field.getName()+"\":"+field.get(obj)+",";
			}else if(field.getType() == String.class){
				jsonStr += "\""+field.getName()+"\":\""+field.get(obj)+"\",";
			}else if(field.getType() == List.class){
				String value = simpleListToJsonStr((List<?>)field.get(obj),claList);
				jsonStr += "\""+field.getName()+"\":"+value+",";				
			}else{		
				if(claList!=null&&claList.size()!=0&&claList.contains(field.getType())){
					String value = simpleObjectToJsonStr(field.get(obj),claList);
					jsonStr += "\""+field.getName()+"\":"+value+",";					
				}else{
					jsonStr += "\""+field.getName()+"\":null,";
				}
			}
		}
		jsonStr = jsonStr.substring(0,jsonStr.length()-1);
		jsonStr += "}";
			return jsonStr;		
	}
	
	/**
	 * 将JAVA的LIST转换成JSON字符串
	 * @param list
	 * @return
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	@SuppressWarnings("rawtypes")
	public static String simpleListToJsonStr(List<?> list,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{
		if(list==null||list.size()==0){
			return "[]";
		}
		String jsonStr = "[";
		for (Object object : list) {
			jsonStr += simpleObjectToJsonStr(object,claList)+",";
		}
		jsonStr = jsonStr.substring(0,jsonStr.length()-1);
		jsonStr += "]";		
		return jsonStr;
	}	
	
	/**
	 * 将JAVA的MAP转换成JSON字符串,
	 * 只转换第一层数据
	 * @param map
	 * @return
	 */
	public static String simpleMapToJsonStr(Map<?,?> map){
		if(map==null||map.isEmpty()){
			return "null";
		}
		String jsonStr = "{";
		Set<?> keySet = map.keySet();
		for (Object key : keySet) {
			jsonStr += "\""+key+"\":\""+map.get(key)+"\",";		
		}
		jsonStr = jsonStr.substring(0,jsonStr.length()-1);
		jsonStr += "}";
		return jsonStr;
	}
}

 
  • 1
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sjiang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值