文章目錄
- 前言
-
- 小技巧-String,json ,Map,jsonObject,各種類型,對象互相轉換
前言
如果您覺得有用的話,記得給部落客點個贊,評論,收藏一鍵三連啊,寫作不易啊^ _ ^。
而且聽說點贊的人每天的運氣都不會太差,實在白嫖的話,那歡迎常來啊!!!
小技巧-String,json ,Map,jsonObject,各種類型,對象互相轉換
一篇代碼直接講解所有:
廢話不多說,上代碼:
測試對象:
class R{
private String a;
private long b;
private Timestamp c;
private Date d;
public void setA(String a) {
this.a = a;
}
public void setB(long b) {
this.b = b;
}
public void setC(Timestamp c) {
this.c = c;
}
public void setD(Date d) {
this.d = d;
}
public String getA() {
return a;
}
public long getB() {
return b;
}
public Timestamp getC() {
return c;
}
public Date getD() {
return d;
}
}
測試類:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Map;
public class Test1 {
private static final String msg = "{\"test\":{\n" +
" \"a\":\"15\",\n" +
" \"b\":\"89\",\n" +
" \"c\":\"2021-06-07 12:12:12\",\n" +
" \"d\":\"2021-05-23 12:12:12\"\n" +
"}}";
public static void main(String[] args) {
//json 轉 Map
Map<String,Object> map = JSONObject.parseObject(msg);
System.out.println("String 轉Map:"+map);
//Map 轉 String
String jsonString = JSON.toJSONString(map.get("test"));
System.out.println("傳參:"+jsonString);
// json 轉 jsonObject
JSONObject jsonObject = JSONObject.parseObject(jsonString);
R r = new R();
//jsonObject 轉各種類型
r.setA(jsonObject.getString("a"));
r.setB(jsonObject.getLongValue("b"));
r.setC(jsonObject.getTimestamp("c"));
r.setD(jsonObject.getSqlDate("d"));
//String 轉對象
R r2 = JSON.parseObject(jsonString,new TypeReference<R>(){
});
//Object 轉 String
String r1 = JSON.toJSONString(r);
System.out.println("R對象轉成String輸出:"+r1);
}
}
觀察結果: