Getting string from json object not working - java

I am using gson library to get the json from an http request.
Everything works fine, except the part where I compare the string I received from the request. Even if the string are exactly the same, for some reason string.equals method fails. And as output it prints always different dates.
What is the reason for this behaviour? What am I missing here?
BufferedReader br;
try{
String url = "http://date.jsontest.com/";
URL request_url = new URL(url);
HttpURLConnection conn = (HttpURLConnection)request_url.openConnection();
conn.setRequestMethod("GET");
if (200 == conn.getResponseCode()){
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String jsonLine = "";
String line ;
while ((line = br.readLine()) != null) {
jsonLine += line;
}
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
try{
String result = jobject.get("date").toString();
System.out.println("res: " + result);
if(result.equals("05-29-2017"))
System.out.println("Same date");
else
System.out.println("different date");
}
catch (NullPointerException ex){ }
}
}
catch (JsonSyntaxException ex){}
catch (IOException ex) {}

String result = jobject.get("date").toString();
The above line returns String representation of date, i.e. with quotes around it : "05-29-2017" and that's why equals method returns false ("\"05-29-2017\"".equals("05-29-2017") will be false due to double quotes in the start and end)
If you want the actual value, you need to use getAsString method, e.g. following should work:
String result = jobject.get("date").getAsString();
if(result.equals("05-29-2017"))
System.out.println("Same date");
else
System.out.println("different date");

Related

JSON from String Builder (Java) - null error

I am building a program using a GET API call to pull artist info in an Eclipse/Java console. I get a good connection to the API that prints out JSON but I'm getting error when trying to pull a specific data point: Cannot invoke "org.json.simple.JSONObject.get(Object)" because "nbalbum" is null
I'm very new to Java and JSON so appreciate pointers here.
Here is my code below with an example JSON return at bottom:
public static void main(String[] args) {
{
}
try {
//scanner for artist name user input in console
Scanner artistscan = new Scanner(System.in); //create scanner
System.out.println("Please enter artist name to search:");
String artistname = artistscan.nextLine(); //turn input into string
System.out.println("Here is how many albums this artist has:");
artistscan.close();
String oldurl = "https://api.deezer.com/search/artist?q="
+artistname+"";
String newurl=oldurl.replaceAll(" ", "");
URL url = new URL(newurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
//Check if connect is made
int responseCode = conn.getResponseCode();
// 200 OK
if (responseCode != 200) {
throw new RuntimeException("HttpResponseCode: " + responseCode);
} else {
StringBuilder informationString = new StringBuilder();
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
informationString.append(scanner.nextLine());
}
//Close the scanner
scanner.close();
//print results
System.out.println(url); //test url is built correctly
System.out.println(informationString);
//Parse JSON results....
// error/returns null:
org.json.simple.parser.JSONParser jsonParser = new JSONParser();
org.json.simple.JSONObject jsonObj = new JSONObject();
jsonObj = (JSONObject) jsonParser.parse(String.valueOf(informationString));
JSONObject nbalbum = (JSONObject) jsonObj.get(0);
System.out.println(nbalbum.get("nb_album"));
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("-------------------------------------");
}}
This is an example JSON return:
{"data":[{"id":566,"name":"Foo Fighters","link":"https:\/\/www.deezer.com\/artist\/566","picture":"https:\/\/api.deezer.com\/artist\/566\/image","picture_small":"https:\/\/e-cdns-images.dzcdn.net\/images\/artist\/54c324b8651addd8c400de22f9dac5c8\/56x56-000000-80-0-0.jpg","picture_medium":"https:\/\/e-cdns-images.dzcdn.net\/images\/artist\/54c324b8651addd8c400de22f9dac5c8\/250x250-000000-80-0-0.jpg","picture_big":"https:\/\/e-cdns-images.dzcdn.net\/images\/artist\/54c324b8651addd8c400de22f9dac5c8\/500x500-000000-80-0-0.jpg","picture_xl":"https:\/\/e-cdns-images.dzcdn.net\/images\/artist\/54c324b8651addd8c400de22f9dac5c8\/1000x1000-000000-80-0-0.jpg","nb_album":37,"nb_fan":4040577,"radio":true,"tracklist":"https:\/\/api.deezer.com\/artist\/566\/top?limit=50","type":"artist"}],"total":1}
Isn't the JSONObject you're getting, have data field & against this field you have JSON array as value. So if this is true, then maybe fetching json array by jsonObj.get("data") & then accessing the value at a certain position would probably work.

cannot pass the json value to function

I am going to get the JSON from the localhost db. Then, I want to put the json into ArrayList. I want to call the parseJSON function. But the JSON is null. Where I should call the function, thanks so much:))
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
StringBuilder sb = new StringBuilder();
InputStream input = con.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
parseJSON(json);
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON(
);
getJSON.execute();
}
private void parseJSON(String json) {
Gson gson = new Gson();
Type type = new TypeToken<List<EssayElement>>(){}.getType();
List<EssayElement> mList = gson.fromJson(json, type);
for (EssayElement essayElement : mList){
Log.i("Message: " +
"", essayElement.id + "-" + essayElement.title + "-" + essayElement.essay + "-" + essayElement.date + "-" + essayElement.time);
}
}
null object reference with String"json"
I would suggest using a proper http library that handles making requests for you like Volley or Retrofit... JSON and Error handling are also builtin, so AsyncTask can completely be removed for that purpose
But what you have is fine, only json shouldn't be used after the while loop, it's only the last line of the http response, not the full json (assuming there's multiple lines)
You should really consider parsing the results in the onPostExecute, and possibly even having the parse method return an actual object, or display to the UI
You are appending the string to StringBuilder sb = new StringBuilder();. You have to call like this parseJSON(sb.toString()); cause String json is just a pointer doesn't hold the actual string, you want.
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
String json = sb.toString();
You can instead use my code snippet it's working fine for me. now you can use son variable for your private void parseJSON(String json) function.

JSON Object GSON into list

I want to implement my old code when I was populating JSON array into listview but my current json haven't specified array, overall json is an array...
Can somebody tell me how to transform my code to use JSON like this?
https://api-v2.hearthis.at/categories/drumandbass/?page=15&count=2
Code to use gson, my old:
protected List<Model> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = new JSONArray("arrayname");
List<Model> dataModelList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
Model modelList = gson.fromJson(finalObject.toString(), Model.class);
dataModelList.add(modelList);
}
return dataModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
Instead of doing this:
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = new JSONArray("arrayname");
Just do this:
JSONArray parentArray = new JSONArray(finalJson);
If i understand the problem correctly, i guess you are having trouble parsing the array who's name is not specified with a key. So, a simple but not a very good way of doing this would be, when you create your finalJson like this:
String finalJson = buffer.toString();
just add a line to check if it contains an array opening bracket, like this:
if(finalJson.contains("[")){
finalJson = finalJson.replace("[","{
"arrayname": [");
}
also, close the array appropriately.
if(finalJson.contains("]")){
finalJson = finalJson.replace("]","]
}");
}
This way, u will have a name for the array to parse, and i guess this is what you are looking for. But this approach might fail if you have more than 1 array in your Json, in that case you will have to use startsWith & endsWith string methods to give a name to your array. But, as of now, from what your Json looks like, this would work.

Parse HTTP JSONObject response in java

From the endpoint "test" I am returning a JSONObject:
#POST("/test")
#PermitAll
public JSONObject test(String name) {
JSONObject jsonval=new JSONObject();
json.put("key1",true);
json.put("key2","test");
return json;
}
in the method that checks the returned value I want to search for value of "key1".
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json = null;
String res = "";
while ((res = in.readLine()) != null) {
json += res + "\n";
}
in.close();
if (jsonData has key1 with value true){
//do sth
}
else{
//do sth else
}
How can I parse the returned JSONObject?
Have you tried constructing the JSONObject from its string representation (see http://www.json.org/javadoc/org/json/JSONObject.html):
JSONObject result = new JSONObject(json)
where json is the string you've read from the InputStream
Note: you might have to strip the last new line char or even omit new lines altogether

php - parse single value to android

I try to write a simple php file, which checks, whether a mysql value exists or not.
For this, I need to parse a simple string from json to android.
e.g: when the value exists, the string is "yes" and when it doesnt exists the string is "no".
Meanwhile I have tried a lot of "solutions", but nothing works.
To do that I usually use this:
$abfrage = "
SELECT
Something
FROM
somewhere
WHERE
This=$that"
;
$link = mysql_query($abfrage) OR die("Error:"+mysql_error());
while($line = mysql_fetch_assoc($link)){
$new=$line;
}
print(json_encode($new));
and in Android:
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
System.out.println(result);
json_data = new JSONObject(result);
String name=(json_data.getString("something"));
Log.e("pass 3", "connection success ");
}
catch(Exception e)
{
Log.e("result:", result.toString());
}
}
This works well, an the the value of the String "name" is the value of "something".
But now my question:
Is it possible to save a string in PHP and parse them to android?
This is what i got:
$abfrage = "SELECT Something FROM somewhere WHERE This = '$that' LIMIT 1";
// Proof whether the value exists or not
$read = mysql_db_query($db, $abfrage);
if (mysql_num_rows($read) == 0){
$value="no";
}
else{
$value="yes";
};
print json_encode($value);
And in JAVA:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/test.php");
HttpResponse response = httpclient.execute(httppost);
String str = EntityUtils.toString(response.getEntity());
System.out.println(""+str); //prints: yes
if(str=="yes") System.out.println("ok"); //not called
if(str=="no") System.out.println("nope"); //not called
I am not sure how you implemented it, but I assume that you execute PHP script from java code with something like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/sample/sample.php");
HttpResponse response = httpclient.execute(httppost);
Then simply use:
String str = EntityUtils.toString(response.getEntity());
Use
Log.d("Title", "Message");
To display messages in Logcat console.
I faced this problem months before:
The problem is, that the String str, not only contains the word "yes". It also contains different letters/symbols, which are not displayed in Android/Eclipse. So you have to manually delete these letters by simply calling substring(int start, int end)
Try this:
String str = EntityUtils.toString(response.getEntity());
int number= str.length();
System.out.println("str-length"+number); //You will see not the length of 3 (for yes)
String s2= str.substring(0, 3); //short the string
System.out.println("String s2"+s2);
if(s2.equals("yes"))Log.d("Titles", str);

Categories

Resources