1.環境
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
2.實體類轉換爲JSONObject
JSONObject.toJSON(實體類);
例:JSONObject.toJSON(entity);
3.實體類轉換爲Json字符串
JSONObject.toJSONString(實體類);
例:JSONObject.toJSONString(entity);
4.Json字符串轉換爲JSONObject
JSONObject.parseObject(Json字符串);
例:JSONObject.parseObject("{\"address\":\"北京\",\"age\":\"18\",\"name\":\"liut\"}");
5.從JSONObject中獲取某個節點值
JSONObject jo = JSONObject.parseObject(Json字符串);
jo.getString(節點Key名稱);
例:jo.getString("name");
6.將JSONObject轉換爲實體類
(實體類類型)JSONObject.toJavaObject(JSONObject對象,實體類類類型);
例:(Entity)JSONObject.toJavaObject(entityJSONObject,Entity.class);
以下爲全部使用例
public static void main(String[] args){
BasCarrier basCarrier = new BasCarrier();
basCarrier.setAction4synchronization("ADD");
basCarrier.setTable4synchronization("bas_carrier");
basCarrier.setCarrierNameCn("");
basCarrier.setCreateTime(new Date());
// 1.將JavaBean轉換爲JSONOBject
JSONObject jo = (JSONObject) JSONObject.toJSON(basCarrier);
// 2.將JavaBean轉換爲json字符串
String joString = JSONObject.toJSONString(basCarrier);
// 3.將json字符串轉換爲JSONObject
JSONObject joResult = JSONObject.parseObject(joString);
// 4.獲取JSONObject中某個節點值
String va = joResult.getString("table4synchronization");
Date d = joResult.getDate("createTime");
// 5.將JSONObject轉換爲JavaBean
BasCarrier bc = (BasCarrier)JSONObject.toJavaObject(joResult,BasCarrier.class);
System.out.println("over");
}