ArrayList<Object> JSON

前端 未结 4 1795
执念已碎
执念已碎 2021-01-22 10:10

I am trying to return JSON data with my restlet. I can return a single item\'s JSON with..

import org.json.JSONObject;

Site aSite = new Site().getSite();   
JSO         


        
4条回答
  •  悲哀的现实
    2021-01-22 10:51

    You coud use Gson library, that handles lists properly, instead.


    Usage example:

    class BagOfPrimitives {
        private int value1;
        private String value2;
        private transient int value3;
        public BagOfPrimitives(int value1, String value2, int value3) {
            this.value1 = value1;
            this.value2 = value2;
            this.value3 = value3;
        }
    }
    
    BagOfPrimitives obj1 = new BagOfPrimitives(1, "abc", 3);
    BagOfPrimitives obj2 = new BagOfPrimitives(32, "gawk", 500);
    List list = Arrays.asList(obj1, obj2);
    Gson gson = new Gson();
    String json = gson.toJson(list);  
    // Now json is [{"value1":1,"value2":"abc"},{"value1":32,"value2":"gawk"}]
    

提交回复
热议问题