数组和Json相互转换

数组转Json

 private void strToJson() {
        JsonArray array = new JsonArray();
        JsonObject object = new JsonObject();
        JsonObject obj = new JsonObject();
        object.addProperty("name", "ta");
        object.addProperty("name2", "ta2");
        array.add(object);
        obj.addProperty("a1", new Gson().toJson(array));
        Log.e("la", obj.toString());
    }

Json转数组

 

listStr=[{"id":0,"name":"我是第0个","age":10},{"id":1,"name":"我是第1个","age":11},{"id":2,"name":"我是第2个","age":12},{"id":3,"name":"我是第3个","age":13},{"id":4,"name":"我是第4个","age":14},{"id":5,"name":"我是第5个","age":15},{"id":6,"name":"我是第6个","age":16},{"id":7,"name":"我是第7个","age":17},{"id":8,"name":"我是第8个","age":18},{"id":9,"name":"我是第9个","age":19}]
 

List jsonListObject = gs.fromJson(listStr, new TypeToken>(){}.getType());//把JSON格式的字符串转为List  
        for (Person p : jsonListObject) {  
            System.out.println("把JSON格式的字符串转为List///  "+p.toString());  
        }  

 

你可能感兴趣的:(android工具)