Ajax -- controller层传json字符串给js时,date类型显示[Object object]解决方法

首先,要先引入一个工具类JsonDateValueProcessor.java

package com.id0304.ssy.util;  
  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.Locale;  
  
import net.sf.json.JsonConfig;  
import net.sf.json.processors.JsonValueProcessor;  
  
public class JsonDateValueProcessor implements JsonValueProcessor {  
  
    private String format ="yyyy-MM-dd";  
      
    public Object processArrayValue(Object value, JsonConfig config) {  
        return process(value);  
    }  
  
    public Object processObjectValue(String key, Object value, JsonConfig config) {  
        return process(value);  
    }  
      
    private Object process(Object value){  
          
        if(value instanceof Date){  
            SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.UK);  
            return sdf.format(value);  
        }  
        return value == null ? "" : value.toString();  
    }  
}

controller层代码

JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor());
JSONArray jsonArray = JSONArray.fromObject(userList, jsonConfig);
String json = jsonArray.toString();

这样得到的字符串json传到js使用时date类型就不会出现[Object object]了.

你可能感兴趣的:(Ajax)