使用alibaba的fastjson
maven坐标
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
类转json
String jsonStr = JSON.toJSONString(accountingScence);
json转为类:
AccountingScence accountingScence = JSONObject.parseObject(json,AccountingScence.class);
Json转为类数组:
List<JournalEntry> journalEntries = new ArrayList<JournalEntry>();
journalEntries = JSONObject.parseArray(resp,JournalEntry.class);
使用net.sf.json-lib
maven坐标
有一点小特殊,需要指定jdk版本
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
类转为Json串
单个对象
import net.sf.json.JSONObject;
//类转为json 用JsonObject
JSONObject json = JSONObject.fromObject(voucherEntrie);
String strJson=json.toString();
System.out.println(strJson);
对象是数组
import net.sf.json.JSONObject;
//数组类转为json,用JsonArray
JSONArray json = JSONArray.fromObject(voucherEntries);
String strJson=json.toString();
Json串转为类
import net.sf.json.JSONObject;
String testJson = "{\"sceneID\":\"02002001\",\"deposit\":\"11000\",\"supplierName\":\"华为荣耀公司\"}";
JSONObject jsonObject=JSONObject.fromObject(testJson);
评论区