I am trying to perform a GET request to https://www.cryptocompare.com/api/data/coinlist/, I am grabbing the values "ImageUrl, "Name", and "CoinName". However, I am only receiving about ~230 values with an "ImageUrl". I should be receiving ~1470. This is the exception I receive. I am confused by this since I do a GET request using Postman and it has a value for every "ImageUrl".
org.json.JSONException: No value for ImageUrl
Here is the code for my GET request
#Override
public void GETCoins() {
String url = "https://www.cryptocompare.com/api/data/coinlist/";
Log.d("Debug ", "URL: " + url);
//Run async task to pull weather data. weatherTask.get... forces main thread to wait for this to finish
HTTPAsyncTask coinTask = new HTTPAsyncTask(this);
coinTask.execute(url, "GET");
try {
JSONObject jsonObject = new JSONObject(coinTask.get());
JSONObject obj = new JSONObject(jsonObject.getString("Data"));
Iterator<?> keys = obj.keys();
int i = 0;
while(keys.hasNext() ) {
String key = (String) keys.next();
if(obj.get(key) instanceof JSONObject) {
JSONObject val = new JSONObject(obj.get(key).toString());
String imageUrl = baseImageUrl + val.getString("ImageUrl");
String name = val.getString("Name");
String currency = val.getString("CoinName");
CryptoData data = new CryptoData(i, currency, 0,0, imageUrl, name);
allCurrencyList.add(data);
i++;
}
}
//updateData(jsonObject);
} catch (InterruptedException | JSONException | ExecutionException e) {
e.printStackTrace();
} finally {
Log.d("Debug ", "Coin API is null");
}
}
Related
I am trying to call another async task inside an OnPostExecute. The 2nd task does not run at all it seems. I am unable to print anything from within to the logs.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json = new JSONObject(result);
JSONArray lignes = json.getJSONArray("lignes");
populatelist(lignes);
}
catch (JSONException e) {
}
}
}
The populatelist function fills an array. Inside this function, I try to call the 2nd async task to get values based on this list.
protected void populatelist(JSONArray lignes){
try {
for(int i=0;i<lignes.length(); i++) {
JSONObject jsonas = lignes.getJSONObject(i);
String fdesignation = jsonas.getString("designation");
String fqtecde = jsonas.getString("qtecde");
String fcode_produit = jsonas.getString("code");
InfoStock(fcode_produit);
items.add(new PickingListProduitItem(fdesignation,"",fqtecde, ""));
}
}
catch(Exception e){
}
}
InfoStock() is the function that is used to return additional from a web service.
protected void InfoStock(String code_produit){
String stockURL = "http://" + mSharedPreferences.getString(Constants.SERVER_IP,"")+"//rest/v2/produit/info/code/"+ code_produit + "?stock=true";
try {
if (mDownloader != null && mDownloader.getStatus() == AsyncTask.Status.RUNNING) {
mDownloader.cancel(true);
mPDialog.dismiss();
}
mPDialog = new ProgressDialog(getApplicationContext());
mDownloader = new XMLDownloader(getApplicationContext(),mPDialog);
byte[][] downloadResults = mDownloader.execute(stockURL).get();
// Read stock info.
String s = new String(downloadResults[0], StandardCharsets.UTF_8);
JSONObject resp = new JSONObject(s);
PrixStockJSONParser psj = new PrixStockJSONParser(resp);
mRepInfoStock = psj.getRepInfoStock();
mRepInfoPrix = psj.getRepInfoPrix();
} catch (Exception ex) {
}
}
I am trying to set a value in the array <> created in the OnPostExecute Method. However there is no error message and the array is not populated at all. Even if I try to print a log from the InfoStock function, it does nothing.
Any suggestions are welcome.
org.json.JSONException: No value for status
Here is my java code method for json parse
java
public void performSearch() {
String url= "http://192.168.0.136/fyp/stitle1.php";
RequestQueue requestQueue = Volley.newRequestQueue(Stitle.this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
//converting the string to json array object
JSONObject array = new JSONObject();
//Log.i("test", " value : " + array.getString("status"));
Log.i("test", " value : " + response.getString("status"));
if (array.getString("status").equals("true")) {
JSONArray jsonArray = array.getJSONArray("search");
Log.i("test", " value : " + array);
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject product = jsonArray.getJSONObject(i);
//adding the product to product list
boolean add = productList.add(new list(
product.getLong("isbn"),
product.getString("title"),
product.getString("authors"),
product.getInt("accession"),
product.getString("publisher"),
product.getInt("pubyear"),
product.getInt("pages"),
product.getInt("rak"),
product.getInt("hr"),
product.getInt("vr"),
product.getLong("barcode")
));
}
} else {
Log.i("test", "else error");
}
} catch (JSONException e) {
e.printStackTrace();
Log.i("test", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Title", searchtitle.getText().toString());
return params;
}
};
requestQueue = Volley.newRequestQueue(Stitle.this);
requestQueue.add(jsObjRequest);
}
Php file to pass parameter to android jsonobject
stitle1.php
php
<?php
// array for JSON response
$response = array();
//set values just in case any thing goes wrong
$response["status"] = 0;
$response["message"] = "Error before start";
// check for post data with isset
if (isset($_POST["Title"])) {
$title = $_POST["Title"];
// You were not using PDO so I dumped your connection and require you to provide...
//...a configuration file for ...
require_once 'connection.php';
// ...these variables
$host = 'localhost';
$db = 'fyp';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try{
// connecting to db with PDO
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT isbn, title, authors, accession, publisher, pubyear, pages, rak, hr, vr, barcode
FROM books
WHERE title LIKE :titleParam';
$titleParam = "%".$title."%";
$stmt = $pdo->prepare($sql);
// Bind the parameter
$stmt->bindParam(':titleParam', $titleParam, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
// success
$response["status"] = 1;
// connection node
$response["books"] = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data = array();
$data["isbn"] = $row["isbn"];
$data["title"] = $row["title"];
$data["authors"] = $row["authors"];
$data["accession"] = $row["accession"];
$data["publisher"] = $row["publisher"];
$data["pubyear"] = $row["pubyear"];
$data["pages"] = $row["pages"];
$data["rak"] = $row["rak"];
$data["hr"] = $row["hr"];
$data["vr"] = $row["vr"];
$data["barcode"] = $row["barcode"];
array_push($response["books"], $data);
}
}
else {
// required field is missing
$response["status"] = 2;
$response["message"] = "No data returned";
}
}
catch (Exception $e){
$response["status"] = 3;
$response["message"] = "Error occurred." . $e->getMessage();
}
}
else {
$response["status"] = 4;
$response["message"] = "Post parameters are not correct";
}
// echoing JSON response
echo json_encode($response);
?>
When I run my application these lines appear on logcat panel
I/test: value : 4
I/test: org.json.JSONException: No value for status
These are two lines appear on logcat which indicate error about that the parameter was not sent properly
We will take this step for step. Lets start with response.
Your PHP code is returning a status value =4 which indicates that you are not getting the parameters sent to the PHP code properly. It is possible that getParams() is not even being called.
Change the getParams() method to look like this:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
try{
String s = searchtitle.getText().toString();
Log.e("Volley request", "getParams called : " + s);
params.put("Title", s);
}
catch(Exception ex){
Log.e("Volley request ERROR", ex.getMessage());
}
return params;
}
For the second part, lets try to deal with the parsing code. Change the code to look like this:
Now regardless of how your php code responds, you will be getting a well formed JSONObject as a response which you can parse and react to it appropriately.
Change the onResponse() part of the code to look like this:
#Override
public void onResponse(JSONObject response) {
// Log.d("Response", response.toString());
try {
//converting the string to json array object
if(response != null){
if(!response.has("status"){
Log.e(TAG, "Something went wrong -- no status key!");
return;
}
else{
int status = response.optInt("status", -1);
if(status == 1){
//There could be quite a few books in this response...
//...you might want to parse in an AsyncTask instead
parseJsonObject(response);
}
else{
String message = response.optString("message", "uups");
Log.e(TAG, "error message = " + message);
return;
}
}
}
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
}
And now to parse the JSONObject:
Map<String, String> booksMap = new HashMap<>();
private void parseJsonObject(JSONObject jsonObject){
try{
if(jsonObject == null) return;
//Not Available!
String na = "NA"
Log.i("test", " value : " + jsonObject.toString());
if(jsonObject.has("books")){
JSONArray array = jsonObject.getJSONArray("books");
for(int i = 0; array.length(); i++){
JSONObject book = array.getJSONObject(i);
Iterator<String> it = book.keys();
while(it.hasNext()){
String key = it.next();
String value = book.optString(key, na);
booksMap.put(key, value);
}
}
}
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
}
I am using json simple
this is my code:
public static String getDetails() {
String name = System.getProperty("user.name");
JSONParser parser = new JSONParser();
File dir = new File("C:\\Users\\" + name + "\\AppData\\Roaming\\.minecraft\\launcher_profiles.json");
if (dir.exists()) {
Object obj = null;
try {
obj = parser.parse(new FileReader("C:\\Users\\" + name + "\\AppData\\Roaming\\.minecraft\\launcher_profiles.json"));
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject = (JSONObject) obj;
String da = (String) jsonObject.get("username");
try {
return obj.toString() + "\n" + da;
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("dir no exist");
}
return null;
}
when i print this out it returns all the text in the json file and it returns null from String 'da' I dont know why because its not null it exist in the file??
JSON file: https://hastebin.com/sirefacado.json
To access the username you have to use the fully qualified path. In your case that is:
String da = (String) ((JSONObject)((JSONObject)jsonObject.get("authenticationDatabase")).get("d46e53840f3f41a2b9e44e2d4d72ebeb")).get("username");
That is, because your username is encapsulated in the following part of the JSON file:
authenticationDatabase: {
d46e53840f3f41a2b9e44e2d4d72ebeb: {
accessToken: "86ccdfsdfsdfsc2c38ec6012a1ccfsdfR",
username: "privater#email.co",
profiles: {
ad4fa7102fb7432cb4e07d471e348c77: {
displayName: "hio"
}
}
}
}
To access the username via the token you have to go via the authenticationDatabase. It may be the case that there are multiple ids, therefore you have to iterate over all the existing ones
For that you can do
JSONObject authDatabase = (JSONObject) jsonObject.get("authenticationDatabase");
for(Object id : authDatabase.keySet()) {
JSONObject authEntry = (JSONObject) authDatabase.get(id);
String username = (String) authDatabase.get("username");
/* now do something with the username.
You can abort after you found the first username
and store it in the da object, or create a list
of existing usernames, ... */
}
Following are the top level keys in the JSON you posted.
{
"settings": {...some data...},
"launcherVersion": {...some data...},
"clientToken": "dbf69db062d5d32b093e7d67ce744d60",
"profiles": {...some data...},
"analyticsFailcount": 0,
"analyticsToken": "f18d7c0f152f5ad44b2a6525e0d5cfa9",
"selectedProfile": "OptiFine",
"authenticationDatabase": {...some data...},
"selectedUser": {...some data...}
}
Your code tries to extract the value of username from the top level.
String da = (String) jsonObject.get("username")
It doesn't contain the key username. Hence, it is print null.
Your statement below is trying to fetch an element named "username" from the root JSON object however, your actual value is nested inside.
String da = (String) jsonObject.get("username");
{
"authenticationDatabase": {
"d46e53840f3f41a2b9e44e2d4d72ebeb": {
"accessToken": "86ccdfsdfsdfsc2c38ec6012a1ccfsdfR",
"username": "privater#email.co",
"profiles": {
"ad4fa7102fb7432cb4e07d471e348c77": {
"displayName": "hio"
}
}
}
}
}
In order to fetch inner element, you need to drill down as follows. Understand that it is not an good idea to hard cord the key inside the "authenticationDatabase" object.
JSONObject jsonObject = (JSONObject) obj;
String da;
try {
JSONObject adb = (JSONObject) jsonObject.get("authenticationDatabase");
JSONObject adbKey = null;
for(Object key:adb.keySet()) {
String sKey = (String) key;
adbKey = (JSONObject) adb.get(sKey);
da = (String) adbKey.get("username");
return obj.toString() + "\n" + da;
}
} catch (Exception e) {
e.printStackTrace();
}
I am trying to use restFB API to get events for several FB companies pages since now until number of days in the future. Somehow it returns nothing. Facebook Graph API returns the results:
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=AmericanChemicalSociety%2Fevents%3Fsince%3Dnow%26until%3D%2B50%20day&version=v2.7
But it is not working when I am trying to implement it in Java:
private Map<String, ArrayList<JsonObject>> fetchEventsForPeriod(Integer daysAhead) {
Map<String, ArrayList<JsonObject>>mapOfEvents = new HashMap<String, ArrayList<JsonObject>>();
if (this.companiesNamesList.size() == 0) {
getCompanies();
}
for (String companyName : this.companiesNamesList) {
ArrayList<JsonObject>companyEventList = new ArrayList<JsonObject>();
Connection<JsonObject> eventListConnection = this.fbClient.fetchConnection(companyName + "/events",
JsonObject.class, Parameter.with("since", "now"), Parameter.with("until", "+ " + daysAhead + " day"));
while (eventListConnection.hasNext()) {
for (List<JsonObject> eventConnectionPage : eventListConnection) {
for (JsonObject event : eventConnectionPage) {
event.put("univNameId", companyName);
String imageURL = formImageURLFromId(event.get("id").toString());
event.put("imageURL", imageURL);
companyEventList.add(event);
}
}
eventListConnection = this.fbClient.fetchConnectionPage(eventListConnection.getNextPageUrl(), JsonObject.class);
}
mapOfEvents.put(companyName, companyEventList);
}
return mapOfEvents;
}
Basically giving me empty results
restFB is initialized correctly and working for other simpler requests:
private final String appAccessToken = "839761616150633|XMK9PSdojx6uCsOmoGccQC7XMTY";
private FacebookClient fbClient;
#SuppressWarnings("deprecation")
public FacebookRestFB() {
this.companiesList = new JsonArray();
this.companiesNamesList = new ArrayList<String>();
try {
this.fbClient = new DefaultFacebookClient(this.appAccessToken, Version.LATEST);
} catch (FacebookException ex) {
ex.printStackTrace(System.err);
}
}
Update #1
The issue is not yet solved. Any suggestion would be greatly appreciated
Once i have parsed a JSON String into a GSON provided JsonObject class, (assume that i do not wish to parse it into any meaningful data objects, but strictly want to use JsonObject), how am i able to modify a field / value of a key directly?
I don't see an API that may help me.
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonObject.html
Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
This works for modifying childkey value using JSONObject.
import used is
import org.json.JSONObject;
ex json:(convert json file to string while giving as input)
{
"parentkey1": "name",
"parentkey2": {
"childkey": "test"
},
}
Code
JSONObject jObject = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);
output:
{
"parentkey1": "name",
"parentkey2": {
"childkey": "data1"
},
}
Since 2.3 version of Gson library the JsonArray class have a 'set' method.
Here's an simple example:
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));
array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));
Another approach would be to deserialize into a java.util.Map, and then just modify the Java Map as wanted. This separates the Java-side data handling from the data transport mechanism (JSON), which is how I prefer to organize my code: using JSON for data transport, not as a replacement data structure.
It's actually all in the documentation.
JSONObject and JSONArray can both be used to replace the standard data structure.
To implement a setter simply call a remove(String name) before a put(String name, Object value).
Here's an simple example:
public class BasicDB {
private JSONObject jData = new JSONObject;
public BasicDB(String username, String tagline) {
try {
jData.put("username", username);
jData.put("tagline" , tagline);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUsername () {
String ret = null;
try {
ret = jData.getString("username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public void setUsername (String username) {
try {
jData.remove("username");
jData.put("username" , username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getTagline () {
String ret = null;
try {
ret = jData.getString("tagline");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static JSONObject convertFileToJSON(String fileName, String username, List<String> list)
throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
JSONObject json = new JSONObject();
String jsonStr = new String(Files.readAllBytes(Paths.get(fileName)));
json = new JSONObject(jsonStr);
System.out.println(json);
JSONArray jsonArray = json.getJSONArray("users");
JSONArray finalJsonArray = new JSONArray();
/**
* Get User form setNewUser method
*/
//finalJsonArray.put(setNewUserPreference());
boolean has = true;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
finalJsonArray.put(jsonObject);
String username2 = jsonObject.getString("userName");
if (username2.equals(username)) {
has = true;
}
System.out.println("user name are :" + username2);
JSONObject jsonObject2 = jsonObject.getJSONObject("languages");
String eng = jsonObject2.getString("Eng");
String fin = jsonObject2.getString("Fin");
String ger = jsonObject2.getString("Ger");
jsonObject2.put("Eng", "ChangeEnglishValueCheckForLongValue");
System.out.println(" Eng : " + eng + " Fin " + fin + " ger : " + ger);
}
System.out.println("Final JSON Array \n" + json);
jsonArray.put(setNewUserPreference());
return json;
}