所需jar包:
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph -->
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
实例:
//集合生成
User user1 = new User("a","aa");
User user2 = new User("b","bb");
List<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
//对象转json
JSONObject jsonObject = JSONObject.fromObject(user1);
String str = jsonObject.toString();
System.out.print(str);
//json转对象
String JSONStr = JSON.toJSONString(str);
User user = JSON.parseObject(str,new TypeReference<User>(){});
//集合转json字符串
JSONArray json = JSONArray.fromObject(list);
String str = json.toString();
System.out.print(str);
//json字符串转集合
String JSONStr = JSON.toJSONString(str);
List<User> busLineList = JSON.parseObject(str,new TypeReference<List<User>>(){});