json串与对象转换

来源:互联网 发布:车辆保养记录查询软件 编辑:程序博客网 时间:2024/06/05 23:00
import java.util.Date;import net.sf.json.JSONObject;import net.sf.json.JsonConfig;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONTokener;public class Json {    public static String toJson(Object resultobj)   {        if (resultobj != null) {             //JSONArray obj = JSONArray.fromObject(resultobj);              JSONObject obj = JSONObject.fromObject(resultobj);            return (obj.toString());        }        return "";    }     /**    * @Title: toJson     * @Description: TODO(这里用一句话描述这个方法的作用)     * @param resultobj    * @param dateformat 时间格式  yyyy-MM-dd HH:mm:ss    * @return    */    public static String toJson(Object resultobj,String dateformat)   {        if (resultobj != null) {            JsonConfig config = new JsonConfig();              config.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor(dateformat));              //JSONArray obj = JSONArray.fromObject(resultobj);              JSONObject obj = JSONObject.fromObject(resultobj,config);            return (obj.toString());        }        return "";    }     /**     * json格式字符串解析     * @param jsonstring     * @return JSONObject     */    public static org.json.JSONObject JsonStringFormat(String jsonstring) {        JSONTokener jsonParser = new JSONTokener(jsonstring);        org.json.JSONObject jsonobject = null;        try {            jsonobject = (org.json.JSONObject) jsonParser.nextValue();        } catch (JSONException e) {            jsonobject = null;        }        return jsonobject;    }    /**     * json格式字符串解析     * @param jsonstring     * @return JSONObject     */    public static JSONArray JsonListFormat(String jsonstring) {        JSONArray jsonarray = null;        try {            jsonarray = new JSONArray(jsonstring);        } catch (JSONException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return jsonarray;    }    /**    * @Title: JsonToList     * @Description: 解析json数据    * @param jsonstr json格式字符串    * @return JSONObject    */    public static JSONObject JsonToList(String jsonstr){        JSONObject jsonObject = JSONObject.fromObject(jsonstr);        return jsonObject;    }}
0 0