package com;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
public class JsonUtil {
/**
*/
public static void main(String[] args) {
System.out.println("----1.0-------");
//1.0 对象和对象数组转json,自定义json字段
JSONArray jsons=new JSONArray();
JSONObject json=new JSONObject();
json.put("id",1);
json.put("name","ssss");
jsons.add(json);
System.out.println(json);
System.out.println(jsons);
System.out.println("----2.0-------");
//2.0 json转对象
String json1 = "{\"id\":\"22\",\"name\":\"乌鲁木齐\"}";
User user = (User)JSON.toJavaObject(JSON.parseObject(json1),User.class);
System.out.println(user.getId()+","+user.getName());
System.out.println("----3.0-------");
//3.0 json转对象数组
List<User> users=new ArrayList<User>();
String json2 = "[{\"id\":\"22\",\"name\":\"乌鲁木齐\"},{\"id\":\"23\",\"name\":\"搜索\"}]";
JSONArray array = JSONArray.parseArray(json2);
for(int i = 0; i < array.size();i++){
JSONObject jobj = (JSONObject)array.get(i);
User user2 = JSON.toJavaObject(jobj,User.class);
users.add(user2);
}
for(User u:users){
System.out.println(u.getName());
}
System.out.println("----4.0-------");
//4.0 将JSON字符串转换为JSON对象
JSONObject json5 = JSON.parseObject("{\"id\":\"22\",\"name\":\"乌鲁木齐\"}");
System.out.println(json5);
System.out.println("----5.0-------");
//5.0 将JSON字符串转换为JavaBean对象
User user5 = JSON.parseObject("{\"id\":\"22\",\"name\":\"乌鲁木齐\"}", User.class);
System.out.println(user5.getName());
System.out.println("----6.0-------");
//6.0 将JavaBean对象转换为JSON字符串
String jsonObject = JSON.toJSONString(user);
System.out.println(jsonObject);
System.out.println("----7.0-------");
//7.0 将JavaBean对象转换为JSON对象
JSONObject userJson = (JSONObject) JSON.toJSON(user);
System.out.println(userJson.toString());
System.out.println("----8.0-------");
//8.0 将JavaBean对象转换为JSON字符串
String jsonObject8 = JSON.toJSONString(users);
System.out.println(jsonObject8);
System.out.println("----9.0-------");
//9.0 date
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));
}
}
package com;
import java.util.Date;
public class User {
private int id;
private String name;
private Date date;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}