Ehsan Akbar Ehsan Akbar - 5 months ago 19
JSON Question

Android JSON - String literal is not properly closed

I'm so new to Android programming I'm trying to read a JSON String, so I created a String with

json
data as you can see in the picture:

enter image description here

As you can see I get an error :
string literal isn't properly closed


I just want to read data from this string for testing, and after working, I will replace the URL.

Answer

You can use this method to create a JSON response object for testing purpose

public static String loadJSONFromAsset(String name, Context context) {
    String json = null;
    try {
        InputStream is = context.getAssets().open(name + ".json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

Into this method pass the name of json that you need to create under assets folder (app/src/main/assets/) and the Context.

Example:

colors.json (Stored in assets folder)

[
  {
    "hex": "#EFDECD",
    "name": "Almond",
    "rgb": "(239, 222, 205)"
  },
  {
    "hex": "#CD9575",
    "name": "Antique Brass",
    "rgb": "(205, 149, 117)"
  },
]

Method Use:

String json = loadJSONFromAsset(colors.json,context);
Comments