json 中对象的转换

public String toString(){
String json="{rid:%d,topic:'%s'/*String*/,user:'%s'/*String*/title:'%s',content:'%s',replyTime:'%s',userIp:'%s'}";

return String.format(json, rid,topic/*主贴对象*/,user/*用户对象*/,title,content,replyTime.toString(),userIp);
}
// Fields

private long rid;
private Topic topic;//引用类型
private User user;//引用类型
private String title;
private String content;
private Date replyTime;
private String userIp;

topic:'%s' 是String类型的,而topic 是类类型的,如何让他们进行转换,因为可能在其他的类中我需要用到转换后的topic!
希望高手帮我解决这个问题,如果此方法不行,请告诉我其他方法的详细情况!谢谢

回答: json 中对象的转换

  1. 以下是以前写的一段代码,就是JSON串与JAVA对象之间互相转换,使用的Jackson-Json,不管嵌套几层都是OK的。

    Jackson-json网站:http://jackson.codehaus.org/

    import java.io.StringWriter;

    import org.codehaus.jackson.JsonGenerator;
    import org.codehaus.jackson.JsonParser;
    import org.codehaus.jackson.map.MappingJsonFactory;
    import org.codehaus.jackson.type.TypeReference;

    /**
     * JSON转换处理工具类
     * 
     * @created 2011-03-08 09:40:08
     */
    public class JsonUtils {
    	/**
    	 * Object对象转换为JSON格式 
    	 * 
    	 * 例如List对象、JavaBean对象、JavaBean对象数组、Map对象、List Map对象
    	 * @param object 传入的Object对象
    	 * @return object的JSON格式字符串
    	 */
    	public static String toJson(Object object) {
    		
    		// Jackson方式转换为Json
    		MappingJsonFactory f = new MappingJsonFactory(); 
    		StringWriter sw = new StringWriter();
    		
    		try {
    			JsonGenerator generator = f.createJsonGenerator(sw);
    			generator.writeObject(object);
    			generator.close();
    
    		} catch (Exception e) {
    			return "";
    		}
    		return sw.toString();
    		
    	}
    
    	/**
    	 * JSON转换为Object对象
    	 * 
    	 * @param jsonString JSON字符串
    	 * @param c 要转换成的类的类型
    	 * @return Object对象
    	 */
    	public static <T> T jsonToObject(String jsonString, Class<T> c){
    
    		if (jsonString == null || "".equals(jsonString)) {
    			return null;
    
    		} else {
    
    			// Jackson方式将Json转换为对象
    			MappingJsonFactory f = new MappingJsonFactory();
    			try {
    				JsonParser parser = f.createJsonParser(jsonString);
    				return parser.readValueAs(c);
    
    			} catch (Exception e) {
    				return null;
    			}
    		}
    	}
    
    	/**
    	 * 数组格式JSON串转换为ObjectList对象
    	 * @param <T> 
    	 * @param jsonString JSON字符串
    	 * @param tr TypeReference,例如: new TypeReference< List<Album> >(){}
    	 * @return ObjectList对象
    	 */
    	public static <T> T jsonToGenericObject(String jsonString, TypeReference<T> tr){
    
    		if (jsonString == null || "".equals(jsonString)) {
    			return null;
    
    		} else {
    
    			// Jackson方式将Json转换为对象
    			MappingJsonFactory f = new MappingJsonFactory();
    			try {
    				JsonParser parser = f.createJsonParser(jsonString);
    				return parser.readValueAs(tr);
    
    			} catch (Exception e) {
    				return null;
    			}
    		}
    	}
    }

Sitemesh装饰器页面如何获得session中对象?

  1. Q
    使用sitemesh装饰全部页面,在页面上显示session中当前用户信息,但是使用EL表达式${session.loginUser}获取session中对象失败。
    如何可以在装饰页面获取session中对象呢?
  2. A
    1. 你的el语法问题:
    ${sessionScope.loginUser}

    el 中的 scop:
    pageScope
    requestScope
    sessionScope

    2. 如果语法对的,检查后台是不是放错了:

    后台用是 Struts 2, 估计你放错Session了。
    Struts 2 提供的 session  在ValueStack 上, 不是传统的 HttpServletSession

    这么取你的session:
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession(true);
    
    session.setAttribute("loginUser", "lvjian700");
    



java 中 Long[] 如何转换成 long[]

  1. Q
    java 中 Long[] 如何转换成 long[]
  2. A
    先找工具类有没有相应处理方法,如果没有再去实现。
    ArrayUtils.toPrimitive(array);

调用net.sf.json.JSONArray和net.sf.json.JSONObject对象抛出异常

  1. Q
    net.sf.json.JSONArray和net.sf.json.JSONObject对象,每当启动服务程序调用这2个对象的方法时就会抛错,放大加粗的地方就是调用抛出异常的地方
    后端调用:
    private void submitData(AffMealsDetalied affMealsDetalied,String jsonStr,AffMeals affMeals){

           List updateList = null;

           List addList = null;

           if(StringUtil.isNotBlank(jsonStr)){

             Map map = JSonUtil.convertToMap(jsonStr);

               if(map.containsKey("addRows")){

                  Object value = map.get("addRows");

                  addList = JSonUtil.paserJsonArray(affMealsDetalied.getClass(),value);

                  Iterator iterator = addList.iterator();

                  while (iterator.hasNext()) {

                      affMealsDetalied = (AffMealsDetalied) iterator.next();

                      affMealsDetalied.setMealsId(affMeals.getMealsId());
                  }
               }
               if(map.containsKey("updateRows")){
                  Object value = map.get("updateRows");
                  updateList = JSonUtil.paserJsonArray(affMealsDetalied.getClass(), value);
               }

               if(map.containsKey("deleteRows")){

                  Object value = map.get("deleteRows");

                  String ids = JSonUtil.convertArrayToString(value, null);

                  if(StringUtil.isNotBlank(ids)){

                      dao.batchDelete(affMealsDetalied, ids);

                  }

               }

           }

           dao.batchSave(addList);

           dao.batchUpdate(updateList);

        }
    页面抛出的错误信息:

    程序发生异常     >>>返回上一页

    异常信息:java.lang.NoSuchMethodError cannot be cast to java.lang.Exception

    详细异常信息:

    java.lang.ClassCastException: java.lang.NoSuchMethodError cannot be cast to java.lang.Exception
        at com.chinasofti.ro.bizframework.core.mvc.ActionInvoker.invoke(Unknown Source)
        at com.chinasofti.ro.bizframework.core.mvc.ActionFilter.doFilter(Unknown Source)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
        at com.chinasofti.ro.bizframework.core.web.filter.LocaleFilter.doFilterInternal(Unknown Source)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
        at com.icss.resourceone.sdk.SdkFilter.doFilter(SdkFilter.java:147)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
        at com.icss.synergy.common.user.sso.SSOClientEx.doFilter(SSOClientEx.java:130)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
        at com.icss.resourceone.sso.client.SSOClient.doFilter(SSOClient.java:90)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:874)
        at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
        at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
        at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
        at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
        at java.lang.Thread.run(Thread.java:662)

  2. A
    实在不行换别的,比如gson也可以。

java中把pdf转换成图片,怎么做?

  1. Q
    java中把pdf转换成图片,怎么做?谢谢!
  2. A
    下面的链接应该能帮助到楼主

    How do I show a PDF in my Swing Application

    https://pdf-renderer.dev.java.net/examples.html

oracle中日期格式转换 现在是23/02/2015 如何转换成2015-02-23

  1. Q
    如题 :oracle中日期格式转换 现在是23/02/2015 如何转换成2015-02-23
  2. A
    如题 :oracle中日期格式转换 现在是23/02/2015 如何转换成2015-02-23

    如果dt=23/02/2015是日期格式:
    to_char(dt,'yyyy-mm-dd')

    如果是dt=23/02/2015是字符格式:
    to_char(to_date(dt,'dd/mm/yyyy'),'yyyy-mm-dd')

使用easyui,json中嵌套的json如何加载

  1. Q
    使用easyui,json中嵌套的json如何加载
    后台通过一般处理程序获取如下json串:
    [{"ID":1,"Name":"tmac","Age":20,"Gender":"男","CID":{"CID":1,"CName":".net","IsDel":false},"IsDel":false},{"ID":2,"Name":"kobe","Age":20,"Gender":"男","CID":{"CID":2,"CName":"php","IsDel":false},"IsDel":false},{"ID":3,"Name":"jordan","Age":20,"Gender":"男","CID":{"CID":3,"CName":"java","IsDel":false},"IsDel":false},{"ID":4,"Name":"james","Age":20,"Gender":"男","CID":{"CID":4,"CName":"ios","IsDel":false},"IsDel":false},{"ID":5,"Name":"nash","Age":20,"Gender":"男","CID":{"CID":1,"CName":".net","IsDel":false},"IsDel":false},{"ID":6,"Name":"harden","Age":20,"Gender":"男","CID":{"CID":2,"CName":"php","IsDel":false},"IsDel":false},{"ID":7,"Name":"yao","Age":20,"Gender":"男","CID":{"CID":3,"CName":"java","IsDel":false},"IsDel":false},{"ID":8,"Name":"wade","Age":20,"Gender":"女","CID":{"CID":3,"CName":"java","IsDel":false},"IsDel":false},{"ID":11,"Name":"durant","Age":20,"Gender":"男","CID":{"CID":2,"CName":"php","IsDel":false},"IsDel":false},{"ID":12,"Name":"westbrook","Age":23,"Gender":"女","CID":{"CID":3,"CName":"java","IsDel":false},"IsDel":false},{"ID":14,"Name":"green","Age":21,"Gender":"女","CID":{"CID":4,"CName":"ios","IsDel":false},"IsDel":false},{"ID":15,"Name":"dumcan","Age":23,"Gender":"男","CID":{"CID":2,"CName":"php","IsDel":false},"IsDel":false}]
    前台代码:
      <tr>
                    <th field="ID" width="50">ID号</th>
                    <th field="Name" width="50">姓名</th>
                    <th field="Age" width="50">年龄</th>
                    <th field="CID.CName" width="50">班级</th>
                    
                </tr>
    但是结果是使用easyui,json中嵌套的json如何加载

    请问如何让CID里的CName加载出来
  2. A
    本帖最后由 showbo 于 2014-10-23 11:12:12 编辑 用formatter配置

    <th field="CID" width="50" data-options="formatter:function(r){return r.CName}">班级</th>

如何将文本框中的数字字符转换成DECIMAL型的值?(急寻高手)

  1. Q
    如何将文本框中的数字字符转换成DECIMAL型的值?
    我需要把DECIMAL值写到数据库中,但不知道如何转换.请高人指点.
  2. A
    convert一下即可

如何HOOK Directx9中对象的成员函数?

  1. Q
    如何HOOK Directx9中对象的成员函数?关键是如何拦截到对象的地址。是在游戏启动后拦截。
    不是先拦截。
  2. A
    COM hook很难

请教各位神仙,如何在win8 store C#开发中实现文字转换成图片

  1. Q
    请教各位神仙,如何在win8 store C#开发中实现文字转换成图片,很简单就一个textbox 控件我想将里面的文字 转换成图片显示出来...求指教啊..请教各位神仙,如何在win8 store C#开发中实现文字转换成图片

    另外为什么我在这个using指令集里面找不到Draw类了?是NETframework升级的原因?
    虚心请教!谢谢!
  2. A
    画到图片里,然后保存。可以用gdi+。。具体怎么做。。STFW。。