将Json字符串转换为实体对象,然后通过实体Bean得到相应的值
2019-04-24 本文已影响0人
Ay鑫
import java.text.SimpleDateFormat;
import com.ay.entity.Bean;
import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
public class test {
public static void main(String[] args) {
//将字符串转换为json对象,然后根据建得到相应的值
String jsonStr = "{\"id\":\"1\",\"name\":\"张三\",\"birthday\":\"2018-05-01 10:11:05\"}";
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
JSONObject obj = JSONObject.fromObject(jsonStr);
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss"}));
Bean bean = (Bean)JSONObject.toBean(obj,Bean.class);
System.out.println(bean.getId());
System.out.println(bean.getName());
System.out.println(sdf.format(bean.getCreateDate()));
}
}