解决嵌套list类型的JSONObject/JSONArray转换成原来list问题。


解决转换过程中,对象的集合类成员变量变成其他类型对象的问题。

public class A {

  private List<B> blist ;

  public A(List<B> temp){

    blist = temp;

  }

  public void setBlist(List<B> temp){

    blist = temp;

  }

  

  public List<B> getBlist(){

    return blist; 

  }

}

public class Mainclass{

  public static void main(String args[]){ 

    List <A> al = new ArrayList<A>();

    List <B> bl = new ArrayList<B>();

    bl.add(new B()); 

    al.add(new A(bl));

    //防止死循环

    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

    //变成了JSONArray的toString 传到前台。

    String result = JSONArray.fromObject(al, jsonConfig).toString();

    //前台stringify array,传到后台再 变回来

    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
    JSONArray jsonarray = JSONArray.fromObject(result);
    List<A> al1= new ArrayList<A>();

    //这里不能直接 使用JSONArray.toCollection() 需要把子类中的collection先处理,然后设置到父类中否则会变成一个别的对象。
    for (int i = 0; i < jsonarray.size(); i++) {
      JSONObject json = jsonarray.getJSONObject(i);
      JSONArray blist = json.getJSONArray("blist");
      @SuppressWarnings("unchecked")
      List<B> blist= (List<B>) JSONArray.toCollection(blist , B.class);
      A ob1 = (GroupProperty) JSONObject.toBean(json, A.class);
      ob1.setBlist(blist);
      al1.add(ob1);

    }

    //这里al1就对了

      System.out.println(al1);

    

  }

 

}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2024 CODEPRJ.COM