1

I have an application where i get a json and read out of it. To test my application a hava a file with the json in it. The problem is that I can´t just as in C# get it from my pc. So I created an assets folder and put my file in it. Now I have this code:

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());

everytime I run this and get to the while loop the debuger says that there is no frame available. I have breakpoints in the loop and after and they never get hit even when I wait for a long time. What am I doing wrong or is there an other better way to get the jsonObject from my text file?

HHHH
  • 49
  • 11

3 Answers3

1

Instead of placing json file in assets folder create raw folder under res directory and place the json file in raw folder.then try this code in Activity

Create a function within activity to get string from the file like this..

        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();
    }

Finally in oncreate select the file from raw folder and pass the inputstream to function to get string from file..like this...

    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();
        }
Vishwa
  • 1,112
  • 1
  • 11
  • 23
  • thanks that worked nearly perfect. I can´t create my json file but the string is sxml is correct so I guess my json is too big or something else is wrong with it. – HHHH Aug 25 '15 at 10:39
  • @HHHH first create json in notepad then save it as filename.json then paste that file in raw folder.before putting .json file in raw folder ensure json inside the file is valid or not using this url..https://jsonformatter.curiousconcept.com/ – Vishwa Aug 25 '15 at 10:42
  • thanks for the link I didn´t know that. It says my json exeeded the max number of characters. Do you know if there is something bigger than JsonObject or something? – HHHH Aug 25 '15 at 10:48
  • @HHHH can't get you..where you are getting that message " json exeeded the max number of characters". – Vishwa Aug 25 '15 at 10:50
  • the link you posted... I entered my json file and it gave me this error – HHHH Aug 25 '15 at 11:05
  • @HHHH can you post your json. – Vishwa Aug 25 '15 at 11:06
  • No I can´t do that... but I guess it is too large – HHHH Aug 25 '15 at 11:10
  • tried it there and it is looking good. So the problem isn´t the json structure i guess... – HHHH Aug 25 '15 at 11:18
  • what is your justification to use `raw` instead of `assets`? – njzk2 Aug 25 '15 at 13:36
  • @njzk2 refer this link:http://stackoverflow.com/questions/9563373/the-reason-for-assets-and-raw-resources-in-android – Vishwa Aug 26 '15 at 04:04
  • ok, but both should work, I don't really understand how switching from one to the other solves the issue – njzk2 Aug 26 '15 at 12:50
0

You can do something like this (for JSONObject): where dbName = filename

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;
}
0

Use the Following code.

   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;
   }
Aown Raza
  • 2,023
  • 13
  • 29