日期:2014-05-16  浏览次数:20512 次

jsonConfig详细使用

一,setCycleDetectionStrategy 防止自包含

Java代码
  1. /**
  2. *这里测试如果含有自包含的时候需要CycleDetectionStrategy
  3. */
  4. publicstaticvoidtestCycleObject(){
  5. CycleObjectobject=newCycleObject();
  6. object.setMemberId("yajuntest");
  7. object.setSex("male");
  8. JsonConfigjsonConfig=newJsonConfig();
  9. jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
  10. JSONObjectjson=JSONObject.fromObject(object,jsonConfig);
  11. System.out.println(json);
  12. }
  13. publicstaticvoidmain(String[]args){
  14. JsonTest.testCycleObject();
  15. }

其中 CycleObject.java是我自己写的一个类:

Java代码
  1. publicclassCycleObject{
  2. privateStringmemberId;
  3. privateStringsex;
  4. privateCycleObjectme=this;
  5. ……//getters&&setters
  6. }

输出 {"sex":"male","memberId":"yajuntest","me":null}

?

二,setExcludes:排除需要序列化成json的属性

Java代码
  1. publicstaticvoidtestExcludeProperites(){
  2. Stringstr="{'string':'JSON','integer':1,'double':2.0,'boolean':true}";
  3. JsonConfigjsonConfig=newJsonConfig();
  4. jsonConfig.setExcludes(newString[]{"double","boolean"});
  5. JSONObjectjsonObject=(JSONObject)JSONSerializer.toJSON(str,jsonConfig);
  6. System.out.println(jsonObject.getString("string"));
  7. System.out.println(jsonObject.getInt("integer"));
  8. System.out.println(jsonObject.has("double"));
  9. System.out.println(jsonObject.has("boolean"));
  10. }
  11. publicstaticvoidmain(String[]args){
  12. JsonTest.testExcludeProperites();
  13. }

?

?

三,setIgnoreDefaultExcludes

Java代码
  1. @SuppressWarnings("unchecked")