Android--gson将list转化为json字符串

在项目中,需要将list转换为json字符串,发送给服务器,在实现过程中先建立一个实体类App,但是得到的只是list的最后一组数据,查找原因:要将new App放在for循环里面,每次新建一个对象就ok了。

具体代码:

public class App {
    String label;
    String packageName;

    public String getPackageName() {
        return packageName;
    }

    public void setPackageName(String packageName) {
        this.packageName = packageName;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }


}

public class JsonInfo {
    public static ArrayList appInfoList;
    public static List apps = new ArrayList<>();
    static App app;
    public static void info() {
        Gson gson = new Gson();
        ApplicationList list = new ApplicationList();
        appInfoList = list.AppList();
        for (AppInfo appInfo : appInfoList) {
            app = new App();
            String label = appInfo.getLabel();
//            Log.e("label",label);
            String packageName = appInfo.getPackageName();
//            Log.e("packageName",packageName);
            app.setLabel(label);
            app.setPackageName(packageName);
            apps.add(app);
        }
        String jsonApp = gson.toJson(apps);
        WriteSd(jsonApp);
    }
    private static void WriteSd(String str)
    {
        try{
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED));
            String foldername = Environment.getExternalStorageDirectory().getPath()+ "/360";
            File folder = new File(foldername);
            if (folder == null || !folder.exists()) {
                folder.mkdir();
            }
            FileOutputStream out = new FileOutputStream(folder.getCanonicalPath()+ "/"+"json.txt");
            out.write(str.getBytes());
            out.close();

        }catch(Exception e){
            e.printStackTrace();
        }

    }
}


你可能感兴趣的