Reputation: 101
I have a JSON like,
{
"Area1": "areacode1",
"Area2": "areacode2",
"Area3" : "areacode3"
}
I want to parse the json and iterate "area" it to autocompletetextview, My code is,
//Reading JSON from local file
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("arealist.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;
}
//parsing and iterating the json...
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
Iterator<String> keys= obj.keys();
while (keys.hasNext())
{
String keyValue = (String)keys.next();
String valueString = obj.getString(keyValue);
Log.d("Details-->",valueString);
}
} catch (JSONException e) {
e.printStackTrace();
}
I am getting the error as "Type mismatch:can't convert JSONObject to JSONArray",I want to know how to convert JSONObject to string and iterate to List.I am new to android so confused how to proceed further Kindly help,Thanks in advance.
Upvotes: 0
Views: 79
Reputation: 2485
After debug the given json by the below code:
String json = "{\n" +
"\n" +
" \"Area1\": \"areacode1\",\n" +
" \"Area2\": \"areacode2\",\n" +
" \"Area3\" : \"areacode3\"\n" +
"\n" +
" }";
try {
JSONObject obj = new JSONObject(json);
Iterator<String> keys= obj.keys();
while (keys.hasNext())
{
String keyValue = (String)keys.next();
String valueString = obj.getString(keyValue);
Log.d("Details-->",valueString);
}
} catch (JSONException e) {
e.printStackTrace();
}
I realize that the way you read which json does not have any problem. The problem is the string return from loadJSONFromAsset
. You must correct the out of that method.
Upvotes: 0
Reputation: 775
try to read arealist.json like this
InputStream inputStream = getContext().getAssets().open("arealist.json");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null){
sb.append(line).append("\n");
}
//parse JSON and store it in the list
String jsonString = sb.toString();
and use this jsonString in JSONobject
Upvotes: 1