JAVA寫JSON的三種方法,java物件轉json資料
阿新 • • 發佈:2019-01-05
今天給大家講一個物件、物件集合轉json資料的三種方法,三種方法最終達到的效果是一樣的。
jsonlib:個人感覺最麻煩的一個需要匯入的包也多,程式碼也相對多一些。Gson:google的。FastJson:阿里巴巴的,個人覺得這個比較好,而且據說這個也是效能最好一個。下面就貼出三種寫法的程式碼,讀者可以任選其一去使用。關於demo裡面所使用的jar包,可以自行去下載,也可以加我QQ我給你:1455465841
Jsonlib:
jar:package json; import java.util.ArrayList; import java.util.List; import net.sf.json.JSONArray; import user.User; public class Jsonlib { public static void main(String[] args) { User user1 = new User(); user1.setUsername("111"); user1.setPassword("111"); User user2 = new User(); user2.setUsername("222"); user2.setPassword("222"); List<User> lists = new ArrayList<User>(); lists.add(user1); lists.add(user2); JSONArray fromObject1 = JSONArray.fromObject(user1); JSONArray fromObject2 = JSONArray.fromObject(lists); String str1 = fromObject1.toString(); String str2 = fromObject2.toString(); System.out.println(str1); //列印結果 //[{"password":"111","username":"111"}] System.out.println(str2); //列印結果 //[{"password":"111","username":"111"},{"password":"222","username":"222"}] } }
Gson:
jar:package json; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import user.User; public class Gson_a { public static void main(String[] args) { User user1 = new User(); user1.setUsername("111"); user1.setPassword("111"); User user2 = new User(); user2.setUsername("222"); user2.setPassword("222"); List<User> lists = new ArrayList<User>(); lists.add(user1); lists.add(user2); Gson gson = new Gson(); String json1 = gson.toJson(user1); System.out.println(json1); //列印結果 //{"username":"111","password":"111"} String json2 = gson.toJson(lists); System.out.println(json2); //列印結果 //[{"username":"111","password":"111"},{"username":"222","password":"222"}] } }
FastJson:
jar:package json; import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSON; import user.User; public class FastJson { public static void main(String[] args) { User user1 = new User(); user1.setUsername("111"); user1.setPassword("111"); //1、單個物件轉換成json String jsonString = JSON.toJSONString(user1); System.out.println(jsonString); //列印結果 //{"password":"111","username":"111"} User user2 = new User(); user2.setUsername("222"); user2.setPassword("222"); List<User> lists = new ArrayList<User>(); lists.add(user1); lists.add(user2); String jsonString2 = JSON.toJSONString(lists); System.out.println(jsonString2); //列印結果 //[{"password":"111","username":"111"},{"password":"222","username":"222"}] } }