当我用app json viewer打开它时,JSON文件为空

时间:2016-06-15 11:41:54

标签: java android json

使用我的代码,当我使用智能手机JSON file的应用打开JSON VIEWER时,该文件为空。我没有看到内容。

为什么?

现在,我将向您展示我在json

中保存文件的代码

先谢谢大家!

public String showResult(View v) throws IOException {
String  result = "";

        JsonObject json = new JsonObject();
        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                json.put("name",p.getName());
                json.put("distance",p.getDistance());
                json.put("quantity",p.getQuantità());

            }
        }
         result=json.toString();

        String path = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/droidText/";

        //FileWriter file=null;

    /*  try {
            file = new FileWriter(path+"filename5.json");
            file.write(result);


        }catch(IOException ie){}
        finally{


            file.flush();
            file.close();
        }*/
        FileWriter file = new FileWriter(path+"filename31.json");
            file.write(result);
            file.close();
            System.out.println("Successfully wrote Json result to file.");
        /*catch(IOException r){

        }*/
        System.out.println(result);
        return result;

    } 

JsonObject类:

private static class JsonObject {
        public void put(String name, String name1) {
        }
    }

2 个答案:

答案 0 :(得分:0)

您从未关闭FileWriter。始终关闭ReaderWriter个对象。

FileWriter file = new FileWriter(path+"filename31.json");
file.write(result);
file.close();

答案 1 :(得分:0)

使用gson.jar
而不是自定义JsonObject使用com.google.gson.JsonObject,它将生成完美的JSON字符串。

 JsonObject json = new JsonObject();
        json.addProperty("name", "s");
        json.addProperty("distance", "2");
        json.addProperty("quantity", "2");

        result = json.toString();

字符串将是:

  

{"名称":" S""距离":" 2""量":& #34; 2"}