此例子菜鸟专用,大神勿扰。有问题欢迎指导
package com.maven.rest.test;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
//字符串判断是否为空
String str = "";
System.out.println(null == str || str.length() == 0);
System.out.println(StringUtils.isEmpty(str));
//字符串和数字之间转换
//int strint=Integer.valueOf(str);
// String bb= String.valueOf(strint);
//System.out.println(strint);
//JSONObject
JSONObject objs = null;
System.out.println(CollectionUtils.isEmpty(objs));
//判断是否存在这个key
// System.out.println(objs.containsKey("city"));
//Map
Map<String,String> map=null;
System.out.println(CollectionUtils.isEmpty(map));
UserInfo info=new UserInfo();
info.setName("zhangsan");
info.setAge(24);
//bean to json // 将JavaBean序列化为JSON文本
JSONObject jsonObj = JSONObject.parseObject(JSON.toJSONString(info));
System.out.println(jsonObj.get("name"));
UserInfo ss = JSONObject.toJavaObject(jsonObj, UserInfo.class);
System.out.println(ss.getName());
String json="{\"name\":\"chenggang\",\"age\":24}";
//反序列化
UserInfo userInfo=JSON.parseObject(json,UserInfo.class);
System.out.println("name:"+userInfo.getName()+", age:"+userInfo.getAge());
Date date=new Date();
//输出毫秒值
System.out.println(JSON.toJSONString(date));
//默认格式为yyyy-MM-dd HH:mm:ss
System.out.println(JSON.toJSONString(date, SerializerFeature.WriteDateUseDateFormat));
//根据自定义格式输出日期
System.out.println(JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat));
// Fastjson API入口类是com.alibaba.fastjson.JSON,常用的序列化操作都可以在JSON类上的静态方法直接完成。
// public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray
// public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject
// public static final <T> T parseObject(String text, Class<T> clazz); // 把JSON文本parse为JavaBean
// public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray
// public static final <T> List<T> parseArray(String text, Class<T> clazz); //把JSON文本parse成JavaBean集合
// public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本
// public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本
// public static final Object toJSON(Object javaObject); 将JavaBean转换为JSONObject或者JSONArray(和上面方法的区别是返回值是不一样的)
// 例1:将Map转成JSON
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("key1", "One");
map1.put("key2", "Two");
String mapJson = JSON.toJSONString(map1);
System.out.println(mapJson);
}
}