json数组与对象类型转换

 

package hb.dto;

import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

public class MyJsonValueProcessor implements JsonValueProcessor {
	private String format = "yyyy-MM-dd";

	public MyJsonValueProcessor() {
	}

	public MyJsonValueProcessor(String format) {
		this.format = format;
	}

	@Override
	public Object processArrayValue(Object value, JsonConfig arg1) {
		String[] obj = {};
		if (value instanceof Date[]) {
			SimpleDateFormat sf = new SimpleDateFormat(format);
			Date[] dates = (Date[]) value;
			obj = new String[dates.length];
			for (int i = 0; i < dates.length; i++) {
				obj[i] = sf.format(dates[i]);
			}
		}
		return obj;
	}

	@Override
	public Object processObjectValue(String key, Object value,
			JsonConfig jsonconfig) {
		if (value instanceof Date) {
			String str = new SimpleDateFormat(format).format((Date) value);
			return str;
		}
		return value.toString();
	}

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}
}

 

 

package hb.dto;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class DateToJson {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 JsonConfig jsonConfig = new JsonConfig();
		 jsonConfig.registerJsonValueProcessor(Date.class,
		           new MyJsonValueProcessor("yyyy-mm-dd"));
		 String str="{'age':12,'name':'huangbiao','birthday':'1999-9-9'}";
		 Map map = new HashMap();
		 map.put("date", new Date());
		 JSONObject json = JSONObject.fromObject(map, jsonConfig);
		 System.out.println(json);
	}

}

  

//字符转日期类型

import java.util.Collection;
import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONArray;
import net.sf.json.util.JSONUtils;

public class JsonToDate {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] { "yyyy-MM-dd" }));
		String jsonStr = "[{'age':12,'name':'huangbiao','birthday':'1999-9-9'}]";
		Collection<Person> list = JSONArray.toCollection(JSONArray.fromObject(jsonStr), Person.class);
		for (Person o : list) {
			System.out.println(o.getBirthday());
		}
	}

}

 

你可能感兴趣的:(json)