【问题标题】:How to get json from textfile in android studio如何从android studio中的文本文件中获取json
【发布时间】:2015-11-18 21:47:30
【问题描述】:

我有一个应用程序,我可以在其中获取一个 json 并从中读出。 要测试我的应用程序,需要一个包含 json 的文件。 问题是我不能像在 C# 中那样从我的电脑中获取它。 所以我创建了一个资产文件夹并将我的文件放入其中。 现在我有了这个代码:

BufferedReader r = null;
AssetManager a = getAssets();
StringBuilder s = new StringBuilder();
try{
r = new BufferedReader(new InputStreamReader(a.open("My.json"), "UTF-8"));
String l;
while((l = r.readLine()) != null){
s.append(l);
}

JSONObject g = new JSONObject(s.toString());

每次我运行它并进入 while 循环时,调试器都会说没有可用的帧。我在循环中和之后都有断点,即使我等待很长时间,它们也不会被击中。 我做错了什么还是有其他更好的方法可以从我的文本文件中获取 jsonObject?

【问题讨论】:

    标签: android json file android-studio


    【解决方案1】:

    不要将 json 文件放在 assets 文件夹中,而是在 res 目录下创建 raw 文件夹并将 json 文件放在 raw 文件夹中。然后在 Activity 中尝试此代码

    在活动中创建一个函数以从文件中获取字符串,如下所示..

            public String readTextFile(InputStream inputStream) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    
            byte buf[] = new byte[1024];
            int len;
            try {
                while ((len = inputStream.read(buf)) != -1) {
                    outputStream.write(buf, 0, len);
                }
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
    
            }
            return outputStream.toString();
        }
    

    最后在 oncreate 中从原始文件夹中选择文件并将输入流传递给函数以从文件中获取字符串......就像这样......

        try {
           //here my json file is jsondata.json which is in raw folder.
           InputStream fileStream=getResources().openRawResource(R.raw.jsondata);
            String sxml = readTextFile(fileStream);
          //here converting the string as json object
        JSONObject json = new JSONObject(sxml);
        TextView text=(TextView)findViewById(R.id.datedemo);
        //here convert the json as string and displayed in textview
        text.setText(json.toString());
    
        }catch (Exception e){
            e.printStackTrace();
            }
    

    【讨论】:

    • 感谢工作几乎完美。我无法创建我的 json 文件,但字符串是 sxml 是正确的,所以我猜我的 json 太大或有其他问题。
    • @HHHH 首先在记事本中创建 json 然后将其保存为 filename.json 然后将该文件粘贴到 raw 文件夹中。在将 .json 文件放入 raw 文件夹之前确保文件中的 json 有效或不使用此 url ..jsonformatter.curiousconcept.com
    • 感谢我不知道的链接。它说我的 json 超出了最大字符数。不知道有没有比 JsonObject 更大的东西?
    • @HHHH 无法得到你..你在哪里得到那个消息“json exeeded the max number of characters”。
    • 你发布的链接...我输入了我的 json 文件,它给了我这个错误
    【解决方案2】:

    你可以这样做(对于 JSONObject): 其中 dbName = 文件名

    public JSONArray getData( Activity act, String dbName ) {
        String jsonString = null;
        InputStream inputStream = null;
        JSONArray data = null;
    
        if (act.getFileStreamPath(dbName).exists()) {
            data = new JSONArray();
    
            try {
                inputStream = act.openFileInput(dbName);
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                ByteArrayBuffer baf = new ByteArrayBuffer(20);
    
                int current = 0;
                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                }
                jsonString = new String(baf.toByteArray());
                data = new JSONArray(jsonString);
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }
    

    【讨论】:

      【解决方案3】:

      使用以下代码。

         try {
          String mFileContent = loadFileContent(); 
          JSONObject mJsonObj = new JSONObject(mFileContent);
      
          } catch (Throwable t) {
              Log.d("TAG", "Could not parse malformed JSON: \n"+ mFileContent);
          }
      
      
          private String loadFileContent()
          {
                  String mFilePath = "yourFilePath";
                  FileInputStream fos = null;
                  String fileContent = "";
                  try {
                      fos = new FileInputStream(mFilePath);
                      int fileSize = fos.available();
                      byte[] bytes = new byte[(int)fileSize];
                      int offset = 0;
                      int count=0; 
                      while (offset < fileSize) {
                          count=fos.read(bytes, offset, fileSize-offset);
                          if (count >= 0)
                              offset += count;
                      }
                      fos.close();
      
                      if(fileSize == 0)
                          return null;
      
                      fileContent = new String(fileContent, "UTF-8");
      
                  } catch (Exception e) {
                      return null;
                  }
      
                  return  fileContent;
         }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-12
        • 2015-12-30
        • 2021-08-04
        • 1970-01-01
        相关资源
        最近更新 更多