Hi I am trying to print a JSON response into a readable form that I can then set to a Textview. This is the code where I am trying to print the JSON response.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.d("json", response);
//Creating JsonObject from response String
JSONObject jsonObject = new JSONObject(response);
//extracting json array from response string
JSONArray jsonArray = jsonObject.getJSONArray("data");
JSONObject jsonRow = jsonArray.getJSONObject(0);
//get value from jsonRow
leaderboardView.setText(jsonArray.toString());
it does print the JSON but in a JSON format. this is the JSON format I am receiving.
{"data":[{"username":"DolanF","score":"4220","rank":"1"},{"username":"reyay","score":"3760","rank":"2"},{"username":"MeghanG","score":"2570","rank":"3"},{"username":"PrimGosling","score":"1360","rank":"4"},{"username":"JakubRozanski","score":"1190","rank":"5"},{"username":"rodyquigley","score":"1120","rank":"6"},{"username":"Kaz835","score":"800","rank":"7"},{"username":"bailey","score":"570","rank":"8"},{"username":"Ellis","score":"430","rank":"9"},{"username":"Joel","score":"390","rank":"10"}]}
my goal is to get the username, rank and score printing in a readable format each row underneath each other.
Change:
jsonArray.toString()
in to:
jsonArray.toString(4)
Parameter (for example 4 - like above) is the number of spaces to indent for each level of nesting.
You can expect this output:
Here you have example in Kotlin how you can get all data as variable:
fun readJson() {
val response =
"{\"data\":[{\"username\":\"DolanF\",\"score\":\"4220\",\"rank\":\"1\"},{\"username\":\"reyay\",\"score\":\"3760\",\"rank\":\"2\"},{\"username\":\"MeghanG\",\"score\":\"2570\",\"rank\":\"3\"},{\"username\":\"PrimGosling\",\"score\":\"1360\",\"rank\":\"4\"},{\"username\":\"JakubRozanski\",\"score\":\"1190\",\"rank\":\"5\"},{\"username\":\"rodyquigley\",\"score\":\"1120\",\"rank\":\"6\"},{\"username\":\"Kaz835\",\"score\":\"800\",\"rank\":\"7\"},{\"username\":\"bailey\",\"score\":\"570\",\"rank\":\"8\"},{\"username\":\"Ellis\",\"score\":\"430\",\"rank\":\"9\"},{\"username\":\"Joel\",\"score\":\"390\",\"rank\":\"10\"}]} \n" +
"\n"
val jsonObject = JSONObject(response)
val jsonArray = jsonObject.getJSONArray("data")
var output = ""
for (position in 0 until jsonArray.length()) {
val row = jsonArray.getJSONObject(position)
val name = row.getString("username")
val score = row.getString("score")
val rank = row.getInt("rank")
output += String.format("%s - %s (rank: %s)\n", name, score, rank)
}
text_view.text = output
}
Or in Java:
void readJson() {
String response =
"{\"data\":[{\"username\":\"DolanF\",\"score\":\"4220\",\"rank\":\"1\"},{\"username\":\"reyay\",\"score\":\"3760\",\"rank\":\"2\"},{\"username\":\"MeghanG\",\"score\":\"2570\",\"rank\":\"3\"},{\"username\":\"PrimGosling\",\"score\":\"1360\",\"rank\":\"4\"},{\"username\":\"JakubRozanski\",\"score\":\"1190\",\"rank\":\"5\"},{\"username\":\"rodyquigley\",\"score\":\"1120\",\"rank\":\"6\"},{\"username\":\"Kaz835\",\"score\":\"800\",\"rank\":\"7\"},{\"username\":\"bailey\",\"score\":\"570\",\"rank\":\"8\"},{\"username\":\"Ellis\",\"score\":\"430\",\"rank\":\"9\"},{\"username\":\"Joel\",\"score\":\"390\",\"rank\":\"10\"}]} \n" +
"\n";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
StringBuilder output = new StringBuilder();
for (int position = 0; position < jsonArray.length(); position++) {
JSONObject row = jsonArray.getJSONObject(position);
String name = row.getString("username");
String score = row.getString("score");
int rank = row.getInt("rank");
output.append(String.format("%s - %s (rank: %s)\n", name, score, rank));
}
text_views.setText(output.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
And output is:
Related
the JSON data from the API I'm using
Part of the code: I've indicated in the code, but I'm not sure what to put:
JSONObject volumeObj = itemsObj.getJSONObject(""); inside the " " based on that API. What can I modify in the code or put in the " " to let me get the objects from the {0}, {1} etc etc?
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
// below line is use to make json object request inside that we
// are passing url, get method and getting json object. .
JsonObjectRequest booksObjrequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressBar.setVisibility(View.GONE);
// inside on response method we are extracting all our json data.
try {
JSONArray itemsArray = response.getJSONArray("result");
for (int i = 0; i < itemsArray.length(); i++) {
JSONObject itemsObj = itemsArray.getJSONObject(i);
**JSONObject volumeObj = itemsObj.getJSONObject("");**
String title = volumeObj.optString("title");
String subtitle = volumeObj.optString("subtitle");
JSONArray authorsArray = volumeObj.getJSONArray("authors");
String publisher = volumeObj.optString("publisher");
String publishedDate = volumeObj.optString("publishedDate");
String description = volumeObj.optString("description");
Did you want to obtain the items of the array? The "result" array contains these objects, so you can just access them with indices:
for (int i = 0; i < itemsArray.length(); i++) {
/* This is the ith object in the array */
JSONObject volumeObj = itemsArray.getJSONObject(i);
String title = volumeObj.optString("title");
String subtitle = volumeObj.optString("subtitle");
JSONArray authorsArray = volumeObj.getJSONArray("authors");
String publisher = volumeObj.optString("publisher");
String publishedDate = volumeObj.optString("publishedDate");
String description = volumeObj.optString("description");
...
}
I have this code to get all information from website, I did it very well and it works, but I got stuck when trying to get "fields" from the site
This is the site url:
http://content.guardianapis.com/search?order-by=newest&show-references=author&show-tags=contributor&q=technology&show-fields=thumbnail&api-key=test
Here is the code and how can I fix it
try {
JSONObject jsonRes = new JSONObject(response);
JSONObject jsonResults = jsonRes.getJSONObject("response");
JSONArray resultsArray = jsonResults.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject oneResult = resultsArray.getJSONObject(i);
String url = oneResult.getString("webUrl");
String webTitle = oneResult.getString("webTitle");
String section = oneResult.getString("sectionName");
String date = oneResult.getString("webPublicationDate");
date = formatDate(date);
JSONArray fields = oneResult.getJSONArray("fields");
JSONArray fieldsArray=oneResult.getJSONArray("fields");
String imageThumbnail= null;
if(fields.length()>0){
imageThumbnail=fields.getJSONObject(0).getString("thumbnail");
}
resultOfNewsData.add(new News(webTitle url, date, section, imageThumbnail));
}
} catch (JSONException e) {
Log.e("FromLoader", "Err parsing response", e);
}
Because the fields object isn't an Array is a JSON object
"fields":{"thumbnail":"https://media.guim.co.uk/fa5ae6ca7c78fdfc4ac0fe4212562e6daf4dfb3d/0_265_4032_2419/500.jpg"}
An array object should contain [ JSON1, JSON2, JSON3 ]
In your case this
JSONArray fields = oneResult.getJSONArray("fields");
becomes this
JSONObject fields = oneResult.getJSONObject("fields");
And I don't understand why are you getting the same data twice - fields and fieldsArray
I'm using Android Networking and by using get, I get the data and this is the API that I'm calling.
String url = baseUrl + "atts_devices?device_serial=eq." + Build.SERIAL + "&select=*,subcompany_id{name}"
and getting the response like this
[{"permit_to_use":null,"min":null,"company_id":"4ed8954c-703e-41b5-94ba-eeb29546e3e3","model":"q1","bus_id":"b6d52ce3-3672-4230-9f9e-a6a465c1c8ea","sam_card":"04042DE2E52080","sim_number":null,"device_serial":"WP18121Q00000410","created_on":"2018-05-24T13:28:28.251004+00:00","remarks":null,"location_id":"ec176824-4cb7-4376-a436-429b529f8b45","id":"36bc07be-7d93-4209-ba15-9c9da7a58c3c","device_name":"wizarpos-ken","is_activated":"1","qrcode":null,"is_assigned":"1","sd_serial":"1510124e436172641068a36718010b00","updated_on":"2018-06-07T09:18:29.365416+00:00","software_serial":null,"subcompany_id":{"name":"MAN LINER"},"sim_serial":"89630317324030972665"}]
notice that subcompany_id has a another JSONArray. how can i get the name inside of it?
I'm using Android Fast Networking and this is the entire process
AndroidNetworking.get(baseUrl + "atts_devices?device_serial=eq." + Build.SERIAL + "&select=*,subcompany_id{name}")
.setPriority(Priority.HIGH)
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
#Override
public void onResponse(JSONArray response) {
Log.e("response", String.valueOf(response));
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jresponse = response.getJSONObject(i);
String raw_id = jresponse.get("id").toString();
String id_string = raw_id;
id_string = id_string.replace("\"", "");
String id_final = String.valueOf(id_string);
String raw_company_id = jresponse.get("company_id").toString();
String company_id_string = raw_company_id;
company_id_string = company_id_string.replace("\"", "");
String company_id_final = String.valueOf(company_id_string);
String raw_subcompany_id = jresponse.get("subcompany_id").toString();
String subcompany_id_string = raw_subcompany_id;
subcompany_id_string = subcompany_id_string.replace("\"", "");
String subcompany_id_final = String.valueOf(subcompany_id_string);
String raw_location_id = jresponse.get("location_id").toString();
String location_id_string = raw_location_id;
location_id_string = location_id_string.replace("\"", "");
String location_id_final = String.valueOf(location_id_string);
String raw_bus_id = jresponse.get("bus_id").toString();
String bus_id_string = raw_bus_id;
bus_id_string = bus_id_string.replace("\"", "");
String bus_id_final = String.valueOf(bus_id_string);
CompanyID = company_id_final;
BusID = bus_id_final;
subCompID = subcompany_id_final;
dbmanager.insertToDeviceInformation(id_final,
company_id_final,
subcompany_id_final,
location_id_final,
bus_id_final);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
Make a new JSONObject JSONObject response = jresponse.get("subcompany_id"), then initialize your String name = response.get("name")
"subcompany_id":{"name":"MAN LINER"}
This is JSONObject not JSONArray, JSONArray start with [{ }]
So you can get "name" with JSONObject like this.
JSONObject jsonObjectSubCompanyId = jresponse.getJSONObject("subcompany_id");
String name = jsonObjectSubCompanyId.getString("name");
This question already has answers here:
JSONArray cannot be converted to JSONObject error
(3 answers)
Closed 6 years ago.
I am having problems; I cannot read inner string from a jsonObject. It says JsonArray cannot be converted into JsonObject.
07-26 13:01:31.910 1798-1901/com.example.phuluso.aafs I/System.out: [{"AccommoAddress":{"AddressID":12,"City":"Johannesburg","InfoUrl":null,"Lattitude":"-26.181321","Longitude":"27.99158","PostalCode":2109,"Street":"22 Ararat Str","Town":"Westdene"},"AccommoDetails":null,"AccommoID":1,"AccommoImages":null,"AccommoName":"West Dunes Properties","AccommoType":"Flat","AccredStatus":"ACCREDITED","AddressId":12,"Capacity":9,"Distance":1,"EndDate":"2017-01-01","NearestCampus":"APK","OwnerId":0,"StartDate":"2016-01-01"}]
Here's my JsonArray. I am trying to read from AccommoAddress, but I get the error below:
[{"AccommoAddress":{"AddressID":12,"City":"Johannesburg","InfoUrl":null,"Lattitude":"-26.181321","Longitude":"27.99158","PostalCode":2109,"Street":"22 Ararat Str","Town":"Westdene"},"AccommoDetails":null,"AccommoID":1,"AccommoImages":null,"AccommoName":"West Dunes Properties","AccommoType":"Flat","AccredStatus":"ACCREDITED","AddressId":12,"Capacity":9,"Distance":1,"EndDate":"2017-01-01","NearestCampus":"APK","OwnerId":0,"StartDate":"2016-01-01"}]
Here's my code
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
List<AccommoNearAPK> data = new ArrayList<>();
progressDialog.dismiss();
JSONObject jsonResponse = null;
try
{
jsonResponse = new JSONObject(result);
JSONArray jsonMainNode = jsonResponse.optJSONArray("AccommoAddress");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String name = jsonChildNode.optString("Street");
String number = jsonChildNode.optString("City");
String date_added = jsonChildNode.optString("Longitude");
String lat = jsonChildNode.optString("Lattitude");
System.out.print("Street"+ name + "City" +number+ "Long" + date_added+" Lat" + lat);
Toast.makeText(MapsActivity.this, date_added + name + number + lat, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(MapsActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
"AccommoAddress" is a JSONObject not a JSONArray. So instead of this..
JSONArray jsonMainNode = jsonResponse.optJSONArray("AccommoAddress");
Try this ..
/*String Accommo = jsonResponse.getString("AccommoAddress");
JSONObject AccomoAddress = new JSONObject(Accommo);*/
//simplifying the above code
JSONObject Accomoaddress = jsonResponse.optJSONObject("AccomoAddress");
String name = AccomoAddress.getString("Street");
String number = AccomoAddress.getString("City");
String date_added = AccomoAddress.getString("Longitude");
String lat = AccomoAddress.getString("Lattitude");
Your response is a JSONArray, not a JSONObject, similarly, AccommoAddress is a JSONObject, not a JSONArray. So you need to change the lines near the top to the following:
JSONArray jsonResponse = null;
try
{
jsonResponse = new JSONArray(result);
JSONObject jsonMainNode = jsonResponse.optJSONObject("AccommoAddress");
I've been experiencing some problems for quite some time trying to load a string that contains an array into a JSONArray.
i get the following string from a web-service which contains the movies array:
{"total":3,"movies":[],"links":{......}"}
i'm looking to convert this array into a JASONArray and show it using a list view.
i'm using the following code and it not working....
protected void onPostExecute(String result) {
Log.d(TAG, "result: " + result);
if (result==null || result.length()==0){
// no result:
return;
}
//clear the list
moviesList.clear();
try {
//turn the result into a JSON object
Log.d(TAG, "create responseObject: ");
JSONObject responseObject = new JSONObject(result);
Log.d(TAG, responseObject.toString());
// get the JSON array named "movies"
JSONArray resultsArray = responseObject.getJSONArray("movies");
Log.d(TAG, "JSONArray lenght: " + resultsArray.length());
// Iterate over the JSON array:
for (int i = 0; i < resultsArray.length(); i++) {
// the JSON object in position i
JSONObject movieObject = resultsArray.getJSONObject(i);
Log.d(TAG, "movieObject (from array) : " + movieObject.toString());
// get the primitive values in the object
String title = movieObject.getString("title");
String details = movieObject.getString("synopsis");
//put into the list:
Movie movie = new Movie(title, details, null,null);
//public Movie(String title, String details, String urlnet, String urldevice) {
moviesList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
//refresh listView:
adapter.notifyDataSetChanged();
}
I was hoping a post here would help me solve the problem.
Change this:
JSONObject responseObject = new JSONObject(result);
to this:
JSONObject responseObject = (JSONObject) JSONValue.parse(result);
and then you can get your JSONArray.