將JSON數據轉換成Java的實體類
阿新 • • 發佈:2017-07-27
return ace arc 出錯 earch 方法 cit from 實體類
思路:首先將JSON格式的數據轉換成JSONObject,然後將JSONObject轉換成Java的實體類(其中類屬性包括List等類型)
Java實體類:
SearchFilter 類
1 public class SearchFilter { 2 private String groupOp; 3 4 private List<SearchRule> rules; 5 6 public String getGroupOp() { 7 return groupOp; 8 }9 10 public void setGroupOp(String groupOp) { 11 this.groupOp = groupOp; 12 } 13 14 public List<SearchRule> getRules() { 15 return rules; 16 } 17 18 public void setRules(List<SearchRule> rules) { 19 this.rules = rules; 20 }
SearchRule 類:
1 public class SearchRule { 2 private String field; 3 private String op; 4 private String data; 5 public String getField() { 6 return field; 7 } 8 public void setField(String field) { 9 this.field = field; 10 } 11 public String getOp() {12 return op; 13 } 14 public void setOp(String op) { 15 this.op = op; 16 } 17 public String getData() { 18 return data; 19 } 20 public void setData(String data) { 21 this.data = data; 22 } 23 24 25 }
解析JSon格式字符串的方法
1 public SearchFilter jsonToSearchFilter(String filters) { 2 SearchFilter searchFilter = null; 3 try { 4 JSONObject jsonobject = JSONObject.fromObject(filters);//將json格式的字符串轉換成JSONObject 對象 5 JSONArray array = jsonobject.getJSONArray("rules"); //如果json格式的字符串裏含有數組格式的屬性,將其轉換成JSONArray,以方便後面轉換成對應的實體 6 List<SearchRule> rules = new ArrayList<SearchRule>(); 7 for (int i = 0; i < array.size(); i++) { 8 JSONObject object = (JSONObject) array.get(i); //將array中的數據進行逐條轉換 9 SearchRule rule = (SearchRule) JSONObject.toBean(object, SearchRule.class); //通過JSONObject.toBean()方法進行對象間的轉換 10 rules.add(rule); 11 } 12 String groupOp = jsonobject.getString("groupOp"); //簡單的直接獲取值 13 searchFilter = new SearchFilter(); //對SearchFilter對象進行組裝 14 searchFilter.setGroupOp(groupOp); 15 searchFilter.setRules(rules); 16 } catch (Exception e) { 17 System.out.println("filters=" + filters.toString() + ".json轉換成實體類出錯"); 18 e.printStackTrace(); 19 } 20 return searchFilter; 21 }
這裏只進行了SearchFilter類中list<SearchRule>rule屬性的對象轉換,因為它是一個SearchRule對象數組,需要單獨拿出來進行json轉換成對象,如果直接對filter進行 SearchFilter進行實體轉換會報錯。如果對象中不含有list,array,map等集合,可以像8-9行一樣進行對象轉換。
測試:
1 public static void main(String[] args) { 2 UserMgmtController con = new UserMgmtController(); 3 String filters="{\"groupOp\": \"OR\",\"rules\": [{\"field\": \"realname\",\"op\": \"eq\","+ 4 "\"data\": \"1234\"},{\"field\": \"cityCode\",\"op\": \"ne\",\"data\": \"5678\"}]}"; 5 SearchFilter searchFilter =con.jsonToSearchFilter(filters); 6 System.out.println("gop="+searchFilter.getGroupOp()+" rules.size="+searchFilter.getRules().size()); 7 }
結果:gop=OR rules.size=2
將JSON數據轉換成Java的實體類