4

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'm trying to do is this: 1) Pull data out of the Google Places API 2) Find Google places that match with places in a static JSON object 3) Place markers on a map based on the matches

I have numbers 1 and 3 working, but would like to know the best way of creating a static (constant) JSON object in my project and using it for step 2.

1
  • Can you not just add a data.json file and add that? Or are you asking how to add the file? Commented Nov 12, 2014 at 16:39

3 Answers 3

8

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)
{
    String str = "";
    try
    {
        AssetManager assetManager = context.getAssets();
        InputStream in = assetManager.open("json.txt");
        InputStreamReader isr = new InputStreamReader(in);
        char [] inputBuffer = new char[100];

        int charRead;
        while((charRead = isr.read(inputBuffer))>0)
        {
            String readString = 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:

public void parseJSON(View view)
{
    JSONObject json = new JSONObject();

    try {
        json = new JSONObject(getJSONString(getApplicationContext()));
    } catch (JSONException e) {
        e.printStackTrace();
    }

   //implement logic with JSON here       
}
Sign up to request clarification or add additional context in comments.

Comments

7

You can just place your JSON file into assets folder. Later on you'll be able to read the file, parse it and use values.

1 Comment

@CanadianCoder you have my blessing to implement it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.