Adding Static Json To An Android Studio Project
I'd like to add static JSON to an Android Studio project which can then be referenced throughout the project. Does anyone know the best method of doing this? In more detail what I'
Solution 1:
The answer posted above is indeed what I'm looking for, but I thought I'd add some of the code I implemented to help others take this problem further:
1) Define JSON object in a txt file in the assets folder
2) Implement a method to extract that object in string form:
private String getJSONString(Context context)
{
Stringstr="";
try
{
AssetManagerassetManager= context.getAssets();
InputStreamin= assetManager.open("json.txt");
InputStreamReaderisr=newInputStreamReader(in);
char [] inputBuffer = newchar[100];
int charRead;
while((charRead = isr.read(inputBuffer))>0)
{
StringreadString= String.copyValueOf(inputBuffer,0,charRead);
str += readString;
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
return str;
}
3) Parse the object in any way you see fit. My method was similar to this:
publicvoidparseJSON(View view)
{
JSONObject json = newJSONObject();
try {
json = newJSONObject(getJSONString(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
//implement logic with JSON here
}
Solution 2:
You should replace the String datatype to StringBuilder in the while loop for the properly optimized solution. So in the while loop instead of concatenating you would append the readString to the str StringBuilder.
str.append(readString);
Post a Comment for "Adding Static Json To An Android Studio Project"