Android Studio: How to parse a JSON Object from Inside of a JSON Array?
By getting first node in array you have obtained address
node so no need to run loop
there, address
object is not an array you can get values directly. Try something like this:
JSONArray array = object.getJSONArray("pollingLocations");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String locationName = jsonObject.getJSONObject("address")
.getString("locationName");
Log.d("locationName", locationName);
JSONArray sourcesArray = jsonObject.getJSONArray("sources");
// run loop to get values from this array
for (int j = 0; j < sourcesArray.length(); j++){
JSONObject source = sourcesArray.getJSONObject(j);
String name = source.getString("name");
}
}
How to Parse a JSON Object In Android
In the end I solved it by using JSONObject.get
rather than JSONObject.getString
and then cast test
to a String
.
private void saveData(String result) {
try {
JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
JSONObject json2 = json.getJSONObject("results");
test = (String) json2.get("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
How to parse the Json response in android?
you can parse current json String to get value
from it as :
// Convert String to json object
JSONObject json = new JSONObject(responseText);
// get LL json object
JSONObject json_LL = json.getJSONObject("LL");
// get value from LL Json Object
String str_value=json_LL.getString("value"); //<< get value here
How to parse json string in Android?
Use JSON classes for parsing e.g
JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");
JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....
How to parse a JSON file with volley
Your data is not a JSONObject
instead it is a JSONArray
so you would use the JSONArrayRequest
from Volley
and not JSONObjectRequest
like you are using. You are probably getting an exception there which you are catching. After you get the JSONArray
this line will give you your station for the first station
JSONObject station = jsonArray.getJSONObject(0).getJSONArray("1").getJSONObject(0);
and
station.getString("motto");
will give you the motto for the station.
This is because your data structure is very complicated. I would suggest making it better and easier to navigate
This is what your code snippet for request should look like
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest("https://api.myjson.com/bins/cd6dh",
new Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
JSONObject station1 = response.getJSONObject(0).getJSONArray("1").getJSONObject(0);
String stationName = station1.getString("motto");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("volley", "error");
}
});
requestQueue.add(jsonArrayRequest);
Turns out that other than the wrong request, you never assigned a listener either. It was null as the second parameter of your request.
Dynamically Parse JSON | Android
Solution:
Please follow the steps below.
First, create a model class:
public class MyResponse {
public int page;
public int pageSize;
public int totalPageCount;
public Map<String, String> data;
(make setter getter for page, pageSize, totalPageCount)
.......
.......
}
then, make a custom class as:
class RedirectionInfoDeserializer implements JsonDeserializer<MyResponse> {
private static final String KEY_PAGE = "page";
private static final String KEY_PAGESIZE = "pageSize";
private static final String KEY_TOTALPAGECOUNT = "totalPageCount";
private static final String KEY_DATA = "data";
@Override
public MyResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
// Read simple String values.
final String page = jsonObject.get(KEY_PAGE).getAsInt();
final String pageSize = jsonObject.get(KEY_PAGESIZE).getAsInt();
final String pageCount = jsonObject.get(KEY_TOTALPAGECOUNT).getAsInt();
// Read the dynamic parameters object.
final Map<String, String> data = readParametersMap(jsonObject);
RedirectionInfo result = new RedirectionInfo();
result.setUri(uri);
result.setHttpMethod(httpMethod);
result.setParameters(parameters);
return result;
}
@Nullable
private Map<String, String> readParametersMap(@NonNull final JsonObject jsonObject) {
final JsonElement paramsElement = jsonObject.get(KEY_DATA);
if (paramsElement == null) {
// value not present at all, just return null
return null;
}
final JsonObject parametersObject = paramsElement.getAsJsonObject();
final Map<String, String> parameters = new HashMap<>();
for (Map.Entry<String, JsonElement> entry : parametersObject.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().getAsString();
data.put(key, value);
}
return data;
}
}
then make a method as:
private Converter.Factory createGsonConverter() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(MyResponse.class, new RedirectionInfoDeserializer());
Gson gson = gsonBuilder.create();
return GsonConverterFactory.create(gson);
}
then, make this change in your Retrofit:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://myserver.com")
.addConverterFactory(createGsonConverter())
.build();
That's it.
Try it, let me know if it works.
Related Topics
Input and Output Binary Streams Using Jersey
Creating Runnable Jar with Gradle
How to Access a Folder Inside of a Resource Folder from Inside My Jar File
Why Do I Need Transaction in Hibernate for Read-Only Operations
Why Hypot() Function Is So Slow
Can CSS in Javafx Be Used for Animations
Javafx - Border Radius <-> Background Color
Android: How to Handle Button Click
Get a JSON Object from a Http Response
Jar Mismatch Found 2 Versions of Android-Support-V4.Jar in the Dependency List
What Kind of Ocr Java Library Should I Use in Android