Ehsan Akbar Ehsan Akbar - 5 months ago 34
JSON Question

Get the value of json file in android

I am using this method to read the JSON file in my Android file:

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


I need to get the value of my json file I mean, hex name rgb one by one.

Answer

Change your loadJSONFromAsset to this:

public static JSONArray loadJSONFromAsset(String name, Context context) {
    String json = null;
    JSONArray jsonArray;
    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");
        jsonArray = new JSONArray(json);
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
    return jsonArray;
}

And when your want to handle your single JSON Object iterate through it like this:

JSONArray tmpArray = loadJSONFromAsset(colors,context);

for (int i = 0; i < tmpArray.length(); i++) {
        JSONObject tmp = tmpArray.getJSONObject(i);
        String hex = tmp.getString("hex");
        String name = tmp.getString("name");
        String rgb = tmp.getString("rgb");
}

To get the single RGB Value you could use split on your rgb String like this:

JSONArray tmpArray = loadJSONFromAsset(colors,context);    

for (int i = 0; i < tmpArray.length(); i++) {
        JSONObject tmp = tmpArray.getJSONObject(i);
        String hex = tmp.getString("hex");
        String name = tmp.getString("name");
        String rgb = tmp.getString("rgb"); 
        String[] rgbArray = rgb.split(", "); //Access these with rgbArray[0]
}