1

I have json file:"document.json" in assets folder

document.json:

{
  "string": "Hello World"
}

Can i do this to get the string in android from a json file?

JSONObject jresponse = new JSONObject(R.assets.document);
string response = jresponse.getString("string");

Am i doing something wrong or is it correct?

Is there any method where we pass .json file and get the required string?

user6007737
  • 49
  • 3
  • 7

1 Answers1

1

No, You have to read the JSON from assets first

 InputStream is = getActivity().getAssets().open("document.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        String myJson = new String(buffer, "UTF-8");

Then you can parse that

JSONObject obj = new JSONObject(myJson);
String myFinalString = obj.getString("")

For further help

Community
  • 1
  • 1
Shree Krishna
  • 8,474
  • 6
  • 40
  • 68
  • initially it gives error `FileNotFound Exception`. then i change file name and remove extension `.json` it works fine now.Thnaks – Ajay Mistry Apr 13 '20 at 08:21