I stumbled upon AcousticBrainz and I am trying to get the data from their database. They give me the API (acousticbrainz.org/api). Unfortunatley I am new to JSON and
I am not exactly sure how to get the info. I am trying to get the info from
http://acousticbrainz.org/8e160042-b451-4f96-b59a-d06831d2ae05/high-level
I know that there are only two JSON Objects. "highlevel" and "metadata"
This is how they present their info
http://acousticbrainz.org/8e160042-b451-4f96-b59a-d06831d2ae05
I am coding in Java and this is what I have
String URL = "http://acousticbrainz.org/8e160042-b451-4f96-b59a-d06831d2ae05/high-level";
String Json = IOUtils.toString(new URL(URL));
JSONObject jo = new JSONObject(Json);
JSONObject jom = new JSONObject(jo.get("metadata"));
System.out.println(jo.names());
System.out.println(jom.names());
System.out.println(jo.get("metadata"));
If you are looking to make API call and get the json data you can use the following code:
URIBuilder builder = new URIBuilder().setScheme("http")
.setHost("acousticbrainz.org")
.setPath("/8e160042-b451-4f96-b59a-d06831d2ae05/high-level");
HttpUriRequest httpUriRequest = new HttpGet(builder.build());
HttpResponse httpResponse = HttpClientBuilder.create().build().execute(httpUriRequest);
String response = EntityUtils.toString(httpResponse.getEntity());
JSONObject jsonObject = new JSONObject(response);
System.out.println(jsonObject.toString());
And if you want to parse the json data and use it you can check the below sample code:
JSONObject metaDataObject = jsonObject.getJSONObject("metadata");
String md5EncodedValue = metaDataObject.getJSONObject("audio_properties")
.getString("md5_encoded");
System.out.println(md5EncodedValue);
if you are using maven then add the following dependency
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20131018</version>
</dependency>
or use this link to download the jar
Related
hi guys i have json response like this
Response response = service.execute(requestSendToNS);
// JSONObject jsonResponse = new JSONObject(response);
//String data = jsonResponse.getString("id");
System.out.println("Response Body : " + response.getBody());
and here the result :
Response Body : [{"status":"success","message":"update success","id":"1404","internalid":2604},{"status":"failed","message":"bad location is already used in another location","id":1405}]
my question is how to getting value "id" from my json response ?
i have try use this code :
// JSONObject jsonResponse = new JSONObject(response);
//String data = jsonResponse.getString("id");
i also have use this
List responseObject = objectMapper.readValue(response.getBody(),List);
but i cannot mapping from json Array to object
but i cannot retreive value from id
Your response body is an array.
[{...},{...}]
That's why you can't get id
String data = jsonResponse.getString("id");
Please have a look JsonReader to read json as JsonArray
https://docs.oracle.com/javaee/7/api/javax/json/JsonReader.html#readObject--
JsonReader jsonReader = Json.createReader(new StringReader(response.getBody()));
JsonArray array = jsonReader.readArray();
JsonObject obj = array.getJsonObject(0);
String data = obj.getString("id");
First, you have to create a class that has the exact same structure as the JSON response, and then you can use ObjectMapper from jackson library to write the JSON to class and read the values from it.
I am trying to create a playlist using the Spotify API, and I am writing the POST request to the Spotify API endpoint in Java. I have also included every available scope from Spotify when I retrieve my access token. This is returning a response with an error message of:
{"error":{"message":"Error parsing JSON.","status":400}}
Here is what I have:
String http = "https://api.spotify.com/v1/users/" + userId + "/playlists";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(http);
JsonObject entityObj = new JsonObject();
JsonObject dataObj = new JsonObject();
dataObj.addProperty("name", "title");
dataObj.addProperty("public", "false");
entityObj.add("data", dataObj);
String dataStringify = GSON.toJson(entityObj);
StringEntity entity = new StringEntity(dataStringify);
post.setEntity(entity);
post.setHeader("Authorization", "Bearer " + accessToken);
post.setHeader("Content-Type", "application/json");
CloseableHttpResponse response = client.execute(post);
System.out
.println("Response Code : " + response.getStatusLine().getStatusCode());
String resp = EntityUtils.toString(response.getEntity());
JSONObject responseObj = new JSONObject(resp);
System.out.println(responseObj);
client.close();
Please let me know if you have any insights into what is wrong.
I am assuming you are using the org.json library as well as Google's Gson library. Using both doesn't make sense in this context. You won't need
String dataStringify = GSON.toJson(entityObj);
as entity Object already is a JSON Object. entityObj.toString() should be enough.
The current JSON Data you are sending looks like this:
{
"data":
{
"name":"title",
"public":"false"
}
}
Spotify ask for an JSON Object like this:
{
"name": "New Playlist",
"public": false
}
You only have to send the Data Object dataObj.
i want to parse some json downloaded from the web in a JSONArray.
Simple thing i think, but can't get it to work.
It seams that the JSON Format is the Problem. I tried different ways
to fix it, but nothing helps.
I download the String with this method:
private String DownloadContent(String URL) {
String result = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
HttpResponse response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch(Exception e) {
Log.e("log_tag", e.toString());
}
return result;
}
After that i try to parse the string to the JSONArray like this:
String resultString = DownloadContent(stringUrl);
JSONArray jArray = new JSONArray(resultString);
but everytime i get this exception:
i test the following to get the JSON right:
result = EntityUtils.toString(response.getEntity(), "UTF-8");
result = StringEscapeUtils.unescapeJson(EntityUtils.toString(response.getEntity()));
this methods changed the string but no time the JSON is valid (tested with this).
In my JSON are things like this:
Meine gr\\u00f6\\u00dfte Leidenschaft ist es
http:\\/\\/bla.de\\/wp-content\\/uploads\\/2014\\/02\\/hello.jpg
What should i do to get it right? I hope someone can help me :)
Thanks!
Looking at the detailMessage, it looks like you are trying to create a JSONArray from JSON that looks like
{"posts": [...]}
That's a JSON object, not an array. You'll need to parse it as a JSONObject and get the array object from it.
JSONObject object = new JSONObject(resultString);
JSONArray array = object.getJSONArray("posts"); // or whatever the method is to get a JSONArray element from the JSONObject
This is assuming you are trying to get the JSON array named posts.
I have an Activity which has three fragments and I am trying to retrieve a JSON file from my server which I will be updating on a daily basis.
My JSON file is located here: http://pagesbyz.com/test.json
Because there are fragments, I used the following code in my MainActivity class:
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Toast.makeText(getApplicationContext(), result, 2000).show();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
What I really need to do is retrieve the TYPE field in my JSON file and separate it into three tabs and put it inside a ListView like this:
I would like to know once I have read the JSON file by using the code on top how do I proceed... Thanks for the help :)
Should I query on each fragment and then look for the TYPE field? Would that be easier?
Curious as to why the Toast did not execute... Here is the pastebin for my main activity: http://pastebin.com/gKTCeH79
What you want to do is use Androids JSONObject and JSONArray to access your json data.
For example since your root is a json array you want to instantiate a JSONArray object from your json data you have.
JSONArray jsonArray = new JSONArray(jsonString);
Now from this array you can grab individual JSONObject for each object in your array.
JSONObject objectOne = new JSONObject(0); // Grabs your first item
From the JSONObject you can now access your three values.
String type = objectOne.get("type") // Will give you the value for type
JSONArray: http://developer.android.com/reference/org/json/JSONArray.html
JSONObject: http://developer.android.com/reference/org/json/JSONObject.html
Another way is to use a framework that lets you deserialize json into Java POJO's (Plain Old Java Objects). Gson is the easiest to use.
The basic idea is you make an object that relates directly to your json objects, after you have this you can easily store your data in java objects and use it however you like.
GSON example:
Gson gson = new Gson();
MyCustomClass obj2 = gson.fromJson(json, MyCustomClass.class);
Where MyCustomClass would contain the variables id, type, and data.
GSON reference: https://sites.google.com/site/gson/gson-user-guide
Good Luck!
So I'm developing an Android app (Java) that posts a JSON object to a web server. I've achieved this, but I'm battling to get the string value to display properly.
Instead of the server receiving "6666666666666", it receives "Ljava.lang.String;#41108be0]". How on earth do I go about fixing this? Here's my code:
protected Boolean doInBackground(String... ID) {
HttpClient httpClient = new DefaultHttpClient();
Date dateTime = new Date();
string deviceID=null;
try {
HttpPost request = new HttpPost("http://192.168.1.89:80/");
JSONObject json = new JSONObject();
json.put("IDNo", ID.toString());
json.put("DTSent", dateTime);
json.put("DeviceID", deviceID);
StringEntity se = new StringEntity(json.toString(), "UTF-8");
se.setContentType("application/json; charset=UTF-8");
request.setEntity(se);
request.setHeader( "Content-Type", "application/json");
}
Please help.
ID is a String-Array not just a string. the ... makes it an array. so either use ID[0] or remove the ... from the function declaration
You are passing in an array of strings (see the three dots?). Try using ID[0] instead.
Here is a useful post: