gson小試牛刀——複雜物件和JSON字串相互轉化
阿新 • • 發佈:2018-12-26
好久沒有寫過Java的程式碼了,之所以寫這個題目,是因為同事的遇到的一個疑問,半小時內恢復功力,將其解決掉。
這裡所說的複雜物件是那種屬性是另外一個型別的類。
下面的例子使用gson,將java物件轉化為json字串,根據一個json字串構造出java物件。
直接上碼:
Province類:
public class Province { public String PName; public String PCode; @Override public String toString() { return "Province [PName=" + PName + ", PCode=" + PCode + "]"; } }
City類:public class City { public String Name; public String Code; public Province province; @Override public String toString() { return "City [Name=" + Name + ", Code=" + Code + ", province=" + province.toString() + "]"; } }
County類:public class County { public String Name; public String Code; public City city; @Override public String toString() { return "County [Name=" + Name + ", Code=" + Code + ", city=" + city.toString() + "]"; } }
Test類,程式入口:
import com.google.gson.*; public class Test { /** * @param args */ public static void main(String[] args) { Province p; City city; County county; p = new Province(); p.PName = "河北"; p.PCode = "130"; city = new City(); city.Code = "6"; city.Name = "保定"; city.province = p; county = new County(); county.city = city; county.Name = "順平縣"; county.Code = "36"; // 以上,構建了一個複雜物件County的例項:county // 建立Gson物件 Gson gson = new GsonBuilder().setPrettyPrinting().create(); // java物件轉化為json字串 String s = gson.toJson(county); System.out.println(s); String s2 = "{'Name':'上地','Code': '03', 'city': {'Name': '海淀','Code':'02','province': {'PName':'北京','PCode':'110'}}}"; // json字串轉換為java物件 County city2 = gson.fromJson(s2, County.class); // 將其輸出 System.out.println(city2); } }
執行結果:
{ "Name": "順平縣", "Code": "36", "city": { "Name": "保定", "Code": "6", "province": { "PName": "河北", "PCode": "130" } } } County [Name=上地, Code=03, city=City [Name=海淀, Code=02, province=Province [PName=北京, PCode=110]]]
體會:gson用著很方便,api很豐富,有類似需求會優先考慮。