How to parse JSON results from Unirest call - java
I'm using the Unirest library to retrieve JSON from a Mashape API. I have the call working using the following code:
HttpResponse<JsonNode> request = Unirest.get(URL)
.header("X-Mashape-Authorization", MASHAPE_AUTH)
.asJson();
This returns my JSON in the form of HttpResponse<JsonNode>, which I am unfamiliar with.
From reading the limited documentation, It seems that I have to call getBody() on the response object in order to get a JsonNode object back. I still have no idea what to do with the JsonNode object however.
What is the best way to begin to parse this data?
Edit:
In case it helps with giving examples, the JSON I want to parse looks like this:
{
"success": "1",
"error_number": "",
"error_message": "",
"results": [
{
"name": "name1",
"formatedName": "Name 1"
},
{
"name": "testtesttest",
"formatedName": "Test Test Test"
},
{
"name": "nametest2",
"formatedName": "Name Test 2"
},
{
"name": "nametest3",
"formatedName": "Name Test 3"
}
]
}
Was trying to figure this out today for myself. The source code is probably the only documentation you're going to get. Here's the tl;dr
// the request from your question
HttpResponse<JsonNode> request = Unirest.get(URL)
.header("X-Mashape-Authorization", MASHAPE_AUTH)
.asJson();
// retrieve the parsed JSONObject from the response
JSONObject myObj = request.getBody().getObject();
// extract fields from the object
String msg = myObj.getString("error_message");
JSONArray results = myObj.getJSONArray();
Here's some more explanation of the spelunking I did:
From the HttpResponse class we can see that getBody() is going to return the instance variable body, which gets assigned on line 92 as:
this.body = (T) new JsonNode(jsonString)
So then we need to look at the JsonNode class. The constructor takes a string representing the JSON to be parsed and attempts to create either a JSONObject or a JSONArray. Those objects come from org.json which is well documented, thankfully.
As the response is easily retrieved as a String, you can use any JSON library you want for deserialzion if you don't want to walk through the JSON manually. I personally am partial to Google's GSON and its ability to easily map your JSON response to an object that you create to match.
HttpRequest request = Unirest.get(/*your request URI*/)
.headers(/*if needed*/)
.queryString(/*if needed*/);
HttpResponse<JsonNode> jsonResponse = request.asJson();
Gson gson = new Gson();
String responseJSONString = jsonResponse.getBody().toString();
MyResponseObject myObject = gson.fromJson(responseJSONString, String.class);
In a JSON string , there are two symbols that guide you through parsing :
{ - indicates a JSONObject
[ - indicates a JSONArray
When parsing a json string, you should go through this items iteratively. To understand how many JsonObjects and JsonArrays you have in your string , and from which you should start parsing, use a json-visualizer tool like this website. for exampl for your string the structure is like this :
As you see, the root object is a JSONObject which consists of an JSONArray with three jsonOnjects. To parse such a structure you can use :
JSONObject jsonobj = new JSONObject(jsonstring);
String result = jsonObject.getString("success");
String error_number = jsonObject.getString("error_number");
String error_message = jsonObject.getString("error_message");
JSON Array jsonarray = jsonobj.getJSONArray();
String[] names = new String[jsonArray.length()];
String[] formattedNames = new String[jsonArray.length()];
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
names [i] = jsonObject.getString("name");
formattedNames [i] = jsonObject.getString("formattedName");
}
There is a Serialization feature in Unirest (probably came out after the answers in 2015 and 2014). With the current version 1.4.9, you can use the handy asObject(Class) and body(Object) methods. Here is an example of deserializing AWS CloudSearch responses.
import java.util.Arrays;
import org.apache.http.HttpStatus;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.ObjectMapper;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
public class UnirestExample {
public class Item {
private String full4kurl;
private String previewurl;
private String description;
#Override
public String toString() {
return "{full4kurl:" + full4kurl + ", previewurl:" + previewurl
+ ", description:" + description + "}";
}
}
public class Hit {
private String id;
private Item fields;
#Override
public String toString() {
return "{id:" + id + ", fields:" + fields + "}";
}
}
public class Hits {
private int found;
private int start;
private Hit[] hit;
#Override
public String toString() {
return "{found:" + found + ", start:" + start + ", hit:"
+ Arrays.toString(hit) + "}";
}
}
public class CloudSearchResult {
private Hits hits;
#Override
public String toString() {
return "{hits:" + hits + "}";
}
}
public static final String END_POINT = "AWS CloudSearch URL";
static {
Unirest.setTimeouts(1000, 5000);
Unirest.setObjectMapper(new ObjectMapper() {
private Gson gson = new GsonBuilder().disableHtmlEscaping()
.create();
#Override
public <T> T readValue(String value, Class<T> valueType) {
return gson.fromJson(value, valueType);
}
#Override
public String writeValue(Object value) {
return gson.toJson(value);
}
});
}
public static void main(String[] args) throws UnirestException {
HttpResponse<CloudSearchResult> response = Unirest.post(END_POINT)
.header("Header", "header").body("body")
.asObject(CloudSearchResult.class);
if (response.getStatus() == HttpStatus.SC_OK) {
CloudSearchResult body = response.getBody();
System.out.println(body);
} else {
throw new RuntimeException("Fail to invoke URL ");
}
}
}
You can retrieve the body of JsonNode and then convert the JsonNode to JSONObject to access the values. In order to access the results, you can convert it to JSONArray.
import org.json.*;
HttpResponse<JsonNode> request = Unirest.get(URL).header("X-Mashape
Authorization", MASHAPE_AUTH).asJson();
JSONObject responsejson = request.getBody().getObject();
JSONArray results = responsejson.getJSONArray("results");
Then you can iterate over each JSONObject in results. For example to get first object in results
JSONObject value = results.getJSONObject(0);
This should work as it worked for me
System.out.println(request.getBody().getObject().toString(2));
sample code
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
public class UnirestClient{
public void getQuestions() throws Exception {
HttpResponse<JsonNode> stack= Unirest.get("https://api.stackexchange.com/2.2/questions").
header("accept", "application/json").
queryString("order","desc").
queryString("sort", "creation").
queryString("filter", "default").
queryString("site", "stackoverflow").
asJson();
System.out.println(stack.getBody().getObject().toString(2));
}
public static void main(String args[]) throws Exception {
JavaHTTPAPIClient client = new JavaHTTPAPIClient();
client.getQuestionsUsingUnirest();
}
}
Response
{
"quota_max": 300,
"items": [
{
"creation_date": 1477998742,
"tags": [
"javascript",
"spring",
"sockjs",
"spring-js",
"sockjs-tornado"
],
"title": "Sockjs 404 not found",
"link": "http://stackoverflow.com/questions/40358911/sockjs-404-not-found",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Sviatlana",
"accept_rate": 71,
"user_type": "registered",
"profile_image": "https://i.stack.imgur.com/J9utH.jpg?s=128&g=1",
"link": "http://stackoverflow.com/users/5288347/sviatlana",
"reputation": 109,
"user_id": 5288347
},
"last_activity_date": 1477998742,
"question_id": 40358911,
"view_count": 2,
"is_answered": false
},
{
"creation_date": 1477998741,
"tags": [
"php",
"html",
"email",
"magento",
"static-block"
],
"title": "Creating a magento email template: custom static block not working",
"link": "http://stackoverflow.com/questions/40358910/creating-a-magento-email-template-custom-static-block-not-working",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Elliot",
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/3ca06bfc99ca77598a8c58aa0945bc8a?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/6914645/elliot",
"reputation": 3,
"user_id": 6914645
},
"last_activity_date": 1477998741,
"question_id": 40358910,
"view_count": 1,
"is_answered": false
},
{
"creation_date": 1477998733,
"tags": [
"vba",
"random",
"macros",
"numbers",
"powerpoint"
],
"title": "Random number Powerpoint as slide change",
"link": "http://stackoverflow.com/questions/40358908/random-number-powerpoint-as-slide-change",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Luca ",
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/50594e4723d9c9235a49385e70fdc347?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/7099333/luca",
"reputation": 1,
"user_id": 7099333
},
"last_activity_date": 1477998733,
"question_id": 40358908,
"view_count": 2,
"is_answered": false
},
{
"creation_date": 1477998717,
"tags": [
"javascript",
"jquery",
"cordova",
"jquery-mobile"
],
"title": "page redirection happening when Go button is pressed on a textbox (jquery/cordova)",
"link": "http://stackoverflow.com/questions/40358903/page-redirection-happening-when-go-button-is-pressed-on-a-textbox-jquery-cordov",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Abhi",
"accept_rate": 58,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/118f3b090dbf70bbb82dd280ed2f4e24?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/5145530/abhi",
"reputation": 536,
"user_id": 5145530
},
"last_activity_date": 1477998717,
"question_id": 40358903,
"view_count": 3,
"is_answered": false
},
{
"creation_date": 1477998684,
"tags": [
"php",
"wordpress",
"for-loop"
],
"title": "Wordpress: looping through alternating post types and outputting featured image",
"link": "http://stackoverflow.com/questions/40358895/wordpress-looping-through-alternating-post-types-and-outputting-featured-image",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "icabob91",
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/4955d4f2e9bcbdee92ef49ffd76c51d6?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/6104799/icabob91",
"reputation": 3,
"user_id": 6104799
},
"last_activity_date": 1477998684,
"question_id": 40358895,
"view_count": 3,
"is_answered": false
},
{
"creation_date": 1477998678,
"tags": [
"python",
"datetime",
"python-3.5",
"timedelta"
],
"title": "datetime difference in python3.5",
"link": "http://stackoverflow.com/questions/40358893/datetime-difference-in-python3-5",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "gansub",
"accept_rate": 85,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/ac74b6d927012828dbd79279614f3e58?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/4033876/gansub",
"reputation": 237,
"user_id": 4033876
},
"last_activity_date": 1477998678,
"question_id": 40358893,
"view_count": 4,
"is_answered": false
},
{
"creation_date": 1477998668,
"tags": [
"arm",
"tensorflow"
],
"title": "Wipe out dropout operations from TensorFlow graph",
"link": "http://stackoverflow.com/questions/40358892/wipe-out-dropout-operations-from-tensorflow-graph",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Dmytro Prylipko",
"accept_rate": 40,
"user_type": "registered",
"profile_image": "https://i.stack.imgur.com/aVfpi.png?s=128&g=1",
"link": "http://stackoverflow.com/users/2641587/dmytro-prylipko",
"reputation": 98,
"user_id": 2641587
},
"last_activity_date": 1477998668,
"question_id": 40358892,
"view_count": 2,
"is_answered": false
},
{
"creation_date": 1477998668,
"tags": [
"c++",
"qt"
],
"title": "Scale a dynamically added widget",
"link": "http://stackoverflow.com/questions/40358891/scale-a-dynamically-added-widget",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "student",
"accept_rate": 88,
"user_type": "registered",
"profile_image": "https://graph.facebook.com/814890818587238/picture?type=large",
"link": "http://stackoverflow.com/users/4621626/student",
"reputation": 43,
"user_id": 4621626
},
"last_activity_date": 1477998668,
"question_id": 40358891,
"view_count": 3,
"is_answered": false
},
{
"creation_date": 1477998642,
"tags": ["sql"],
"title": "SQL returning different rows based on certain conditions",
"link": "http://stackoverflow.com/questions/40358889/sql-returning-different-rows-based-on-certain-conditions",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "clueless83",
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/c99db40aa014047b39b6e8222c120d84?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/6720789/clueless83",
"reputation": 18,
"user_id": 6720789
},
"last_activity_date": 1477998642,
"question_id": 40358889,
"view_count": 10,
"is_answered": false
},
{
"creation_date": 1477998626,
"tags": [
"angularjs",
"select",
"multiple-select"
],
"title": "Angular: Select multiple in chrome ( in firefox work perfectly)",
"link": "http://stackoverflow.com/questions/40358886/angular-select-multiple-in-chrome-in-firefox-work-perfectly",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Enrique Rubio Sanchez",
"user_type": "registered",
"profile_image": "https://lh3.googleusercontent.com/-jKUZPfGsMEY/AAAAAAAAAAI/AAAAAAAAAHY/aisyHc_Xlm4/photo.jpg?sz=128",
"link": "http://stackoverflow.com/users/5496817/enrique-rubio-sanchez",
"reputation": 11,
"user_id": 5496817
},
"last_activity_date": 1477998626,
"question_id": 40358886,
"view_count": 5,
"is_answered": false
},
{
"creation_date": 1477998622,
"tags": [
"c#",
"coloranimation"
],
"title": "Cannot animate the color property because the object is sealed or frozen",
"link": "http://stackoverflow.com/questions/40358884/cannot-animate-the-color-property-because-the-object-is-sealed-or-frozen",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Wobbles",
"accept_rate": 63,
"user_type": "registered",
"profile_image": "https://graph.facebook.com/100003846611758/picture?type=large",
"link": "http://stackoverflow.com/users/3797778/wobbles",
"reputation": 1691,
"user_id": 3797778
},
"last_activity_date": 1477998622,
"question_id": 40358884,
"view_count": 3,
"is_answered": false
},
{
"creation_date": 1477998619,
"tags": [
"paypal",
"laravel-5.2",
"paypal-rest-sdk"
],
"title": "Integrating Paypal Rest API to laravel 5.2 using anouarabdsslm",
"link": "http://stackoverflow.com/questions/40358882/integrating-paypal-rest-api-to-laravel-5-2-using-anouarabdsslm",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Ankit Jindal",
"user_type": "registered",
"profile_image": "https://graph.facebook.com/100001546390988/picture?type=large",
"link": "http://stackoverflow.com/users/4198180/ankit-jindal",
"reputation": 6,
"user_id": 4198180
},
"last_activity_date": 1477998619,
"question_id": 40358882,
"view_count": 2,
"is_answered": false
},
{
"creation_date": 1477998605,
"tags": [
"decimal",
"dynamics-crm-2016",
"editablegrid"
],
"title": "Dynamcis CRM EditableGrid sdoesn't sets quantity to 0",
"link": "http://stackoverflow.com/questions/40358881/dynamcis-crm-editablegrid-sdoesnt-sets-quantity-to-0",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "ODE",
"accept_rate": 71,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/3607bfe0c1a853e890ff5c746e793856?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/3332226/ode",
"reputation": 82,
"user_id": 3332226
},
"last_activity_date": 1477998605,
"question_id": 40358881,
"view_count": 2,
"is_answered": false
},
{
"creation_date": 1477998604,
"tags": [
"reporting-services",
"parameters",
"mdx"
],
"title": "MDX (SSRS) Parameter subset",
"link": "http://stackoverflow.com/questions/40358880/mdx-ssrs-parameter-subset",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "user2181700",
"accept_rate": 67,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/a973bbc5607eb4bf001c1d0587c2035d?s=128&d=identicon&r=PG",
"link": "http://stackoverflow.com/users/2181700/user2181700",
"reputation": 40,
"user_id": 2181700
},
"last_activity_date": 1477998604,
"question_id": 40358880,
"view_count": 2,
"is_answered": false
},
{
"creation_date": 1477998588,
"tags": [
"bash",
"chef-recipe"
],
"title": "How can I loop through bash routine in Chef?",
"link": "http://stackoverflow.com/questions/40358877/how-can-i-loop-through-bash-routine-in-chef",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "user5241806",
"accept_rate": 38,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/f93135e0156fd5d3ecba4935a42c0c47?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/5241806/user5241806",
"reputation": 63,
"user_id": 5241806
},
"last_activity_date": 1477998588,
"question_id": 40358877,
"view_count": 3,
"is_answered": false
},
{
"creation_date": 1477998584,
"tags": [
"entity-framework",
"asp.net-web-api",
"unity-container"
],
"title": "Dependency injection not working in web api call",
"link": "http://stackoverflow.com/questions/40358875/dependency-injection-not-working-in-web-api-call",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Tom",
"accept_rate": 71,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/71cd701f6826481858ee299f68f3205a?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/4607841/tom",
"reputation": 94,
"user_id": 4607841
},
"last_activity_date": 1477998584,
"question_id": 40358875,
"view_count": 5,
"is_answered": false
},
{
"creation_date": 1477998573,
"tags": [
"c++",
"windows",
"process",
"kill",
"termination"
],
"title": "How to prevent a windows application from being killed/terminate or stop",
"link": "http://stackoverflow.com/questions/40358872/how-to-prevent-a-windows-application-from-being-killed-terminate-or-stop",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Ankush Dhingra",
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/136386aece9fd21861cb2b42f24f81b6?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/7099310/ankush-dhingra",
"reputation": 1,
"user_id": 7099310
},
"last_activity_date": 1477998573,
"question_id": 40358872,
"view_count": 6,
"is_answered": false
},
{
"creation_date": 1477998556,
"tags": [
"python",
"azure",
"arm",
"azure-sdk-python"
],
"title": "Azure python sdk for VM Resource Monitoring",
"link": "http://stackoverflow.com/questions/40358870/azure-python-sdk-for-vm-resource-monitoring",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "KMG",
"accept_rate": 26,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/3632d43837fe92fda15ddf3b6ad5a8c2?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/3524468/kmg",
"reputation": 158,
"user_id": 3524468
},
"last_activity_date": 1477998556,
"question_id": 40358870,
"view_count": 3,
"is_answered": false
},
{
"creation_date": 1477998521,
"tags": [
"javascript",
"arrays",
"for-loop"
],
"title": "JavaScript array 2 dimension for loop",
"link": "http://stackoverflow.com/questions/40358865/javascript-array-2-dimension-for-loop",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Rayan Suryadikara",
"accept_rate": 80,
"user_type": "registered",
"profile_image": "https://graph.facebook.com/959947287411964/picture?type=large",
"link": "http://stackoverflow.com/users/5355995/rayan-suryadikara",
"reputation": 28,
"user_id": 5355995
},
"last_activity_date": 1477998521,
"question_id": 40358865,
"view_count": 24,
"is_answered": false
},
{
"creation_date": 1477998512,
"tags": [
"javascript",
"user-interface",
"kendo-ui",
"grid"
],
"title": "How to set the number format for hyperlinks in kendo grid column",
"link": "http://stackoverflow.com/questions/40358863/how-to-set-the-number-format-for-hyperlinks-in-kendo-grid-column",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Harsha vardhan Reddy",
"user_type": "registered",
"profile_image": "https://lh6.googleusercontent.com/-tnuvSHlig1U/AAAAAAAAAAI/AAAAAAAAAdU/pBo7JDjmBpM/photo.jpg?sz=128",
"link": "http://stackoverflow.com/users/6323557/harsha-vardhan-reddy",
"reputation": 1,
"user_id": 6323557
},
"last_activity_date": 1477998512,
"question_id": 40358863,
"view_count": 2,
"is_answered": false
},
{
"creation_date": 1477998507,
"tags": [
"android",
"achartengine"
],
"title": "aChartEngine; getCurrentSeriesAndPoint returns null",
"link": "http://stackoverflow.com/questions/40358862/achartengine-getcurrentseriesandpoint-returns-null",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Hyunin",
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/ddaf10ed143d2d44f9a1de00dc6465ec?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/7099269/hyunin",
"reputation": 1,
"user_id": 7099269
},
"last_activity_date": 1477998507,
"question_id": 40358862,
"view_count": 2,
"is_answered": false
},
{
"creation_date": 1477998499,
"tags": [
"c#",
"selenium",
"selenium-chromedriver"
],
"title": "Uploading a file with Selenium C#",
"link": "http://stackoverflow.com/questions/40358860/uploading-a-file-with-selenium-c",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Hoverlord",
"user_type": "registered",
"profile_image": "https://lh4.googleusercontent.com/-5spNCjwaRtU/AAAAAAAAAAI/AAAAAAAADUo/CWI4U9m0VWw/photo.jpg?sz=128",
"link": "http://stackoverflow.com/users/7099290/hoverlord",
"reputation": 1,
"user_id": 7099290
},
"last_activity_date": 1477998499,
"question_id": 40358860,
"view_count": 4,
"is_answered": false
},
{
"creation_date": 1477998487,
"tags": [
"javascript",
"unit-testing",
"angular2",
"typescript",
"jasmine"
],
"title": "Angular 2 with jasmine: test component with injected service",
"link": "http://stackoverflow.com/questions/40358858/angular-2-with-jasmine-test-component-with-injected-service",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "DavidL",
"accept_rate": 81,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/ce4583fa48bbd2e762ba0a9aaeab7909?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/4656551/davidl",
"reputation": 483,
"user_id": 4656551
},
"last_activity_date": 1477998487,
"question_id": 40358858,
"view_count": 5,
"is_answered": false
},
{
"creation_date": 1477998486,
"tags": [
"c#",
"jquery",
"ajax",
"routes",
"asp.net-core-mvc"
],
"title": "asp.net core id value in route doesn't work with ajax",
"link": "http://stackoverflow.com/questions/40358857/asp-net-core-id-value-in-route-doesnt-work-with-ajax",
"last_edit_date": 1477998683,
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Anton Toshik",
"accept_rate": 86,
"user_type": "registered",
"profile_image": "https://graph.facebook.com/1259984217361793/picture?type=large",
"link": "http://stackoverflow.com/users/5784635/anton-toshik",
"reputation": 27,
"user_id": 5784635
},
"last_activity_date": 1477998683,
"question_id": 40358857,
"view_count": 9,
"is_answered": false
},
{
"creation_date": 1477998481,
"tags": [
"python",
"string",
"python-3.x",
"machine-learning",
"string-matching"
],
"title": "how to generate a set of similar strings in python",
"link": "http://stackoverflow.com/questions/40358855/how-to-generate-a-set-of-similar-strings-in-python",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "daiyue",
"accept_rate": 82,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/55fd0f7d95a4938975026ff886c3a563?s=128&d=identicon&r=PG",
"link": "http://stackoverflow.com/users/766708/daiyue",
"reputation": 806,
"user_id": 766708
},
"last_activity_date": 1477998481,
"question_id": 40358855,
"view_count": 8,
"is_answered": false
},
{
"creation_date": 1477998477,
"tags": [
"java",
"mysql",
"swing",
"connection-pooling"
],
"title": "Does Connection Pooling makes Java Swing Application works faster for remote MySQL database",
"link": "http://stackoverflow.com/questions/40358852/does-connection-pooling-makes-java-swing-application-works-faster-for-remote-mys",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "user2200561",
"accept_rate": 25,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/1b7fb8ee134a1d1fdb25350e74c3322c?s=128&d=identicon&r=PG",
"link": "http://stackoverflow.com/users/2200561/user2200561",
"reputation": 8,
"user_id": 2200561
},
"last_activity_date": 1477998477,
"question_id": 40358852,
"view_count": 5,
"is_answered": false
},
{
"creation_date": 1477998469,
"tags": [
"python",
"apache",
"hadoop",
"mapreduce",
"apache-pig"
],
"title": "Apache Pig - nested FOREACH over same relation",
"link": "http://stackoverflow.com/questions/40358849/apache-pig-nested-foreach-over-same-relation",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "user2817219",
"accept_rate": 60,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/89b91c209b145ead1e1a4309fc048afc?s=128&d=identicon&r=PG&f=1",
"link": "http://stackoverflow.com/users/2817219/user2817219",
"reputation": 65,
"user_id": 2817219
},
"last_activity_date": 1477998469,
"question_id": 40358849,
"view_count": 4,
"is_answered": false
},
{
"creation_date": 1477998456,
"tags": [
"mysql",
"laravel-5",
"eloquent"
],
"title": "column overridden by another column with same name when using join method in eloquent",
"link": "http://stackoverflow.com/questions/40358846/column-overridden-by-another-column-with-same-name-when-using-join-method-in-elo",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Mazino S Ukah",
"accept_rate": 100,
"user_type": "registered",
"profile_image": "https://graph.facebook.com/933943226659646/picture?type=large",
"link": "http://stackoverflow.com/users/5746074/mazino-s-ukah",
"reputation": 125,
"user_id": 5746074
},
"last_activity_date": 1477998456,
"question_id": 40358846,
"view_count": 5,
"is_answered": false
},
{
"creation_date": 1477998428,
"tags": [
"javascript",
"http",
"caching",
"browser"
],
"title": "Tell the browser to drop cache of image",
"link": "http://stackoverflow.com/questions/40358839/tell-the-browser-to-drop-cache-of-image",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "php_nub_qq",
"accept_rate": 86,
"user_type": "registered",
"profile_image": "https://i.stack.imgur.com/daMab.jpg?s=128&g=1",
"link": "http://stackoverflow.com/users/2415293/php-nub-qq",
"reputation": 5811,
"user_id": 2415293
},
"last_activity_date": 1477998428,
"question_id": 40358839,
"view_count": 8,
"is_answered": false
},
{
"creation_date": 1477998422,
"tags": [
"ios",
"certificate",
"keychain",
"p12"
],
"title": "Keychain asking password for importing p12 but i didn't give password",
"link": "http://stackoverflow.com/questions/40358836/keychain-asking-password-for-importing-p12-but-i-didnt-give-password",
"score": 0,
"answer_count": 0,
"owner": {
"display_name": "Olcay Erta?",
"accept_rate": 92,
"user_type": "registered",
"profile_image": "https://www.gravatar.com/avatar/f164c6c3b709c97862a0d14f7725830b?s=128&d=identicon&r=PG",
"link": "http://stackoverflow.com/users/614065/olcay-erta%c5%9f",
"reputation": 1129,
"user_id": 614065
},
"last_activity_date": 1477998422,
"question_id": 40358836,
"view_count": 2,
"is_answered": false
}
],
"has_more": true,
"quota_remaining": 298
}
// try this way,hope this will help you...
String respone = "{\n" +
" \"success\": \"1\",\n" +
" \"error_number\": \"\",\n" +
" \"error_message\": \"\",\n" +
" \"results\": [\n" +
" {\n" +
" \"name\": \"name1\",\n" +
" \"formatedName\": \"Name 1\"\n" +
" },\n" +
" {\n" +
" \"name\": \"testtesttest\",\n" +
" \"formatedName\": \"Test Test Test\"\n" +
" },\n" +
" {\n" +
" \"name\": \"nametest2\",\n" +
" \"formatedName\": \"Name Test 2\"\n" +
" },\n" +
" {\n" +
" \"name\": \"nametest3\",\n" +
" \"formatedName\": \"Name Test 3\"\n" +
" }\n" +
" ]\n" +
"}";
try{
JSONObject responeJson = new JSONObject(respone);
if(responeJson.getString("success").equals("1")){
JSONArray jsonArray = responeJson.getJSONArray("results");
for (int i=0;i<jsonArray.length();i++){
System.out.println("Name : "+jsonArray.getJSONObject(i).getString("name"));
System.out.println("FormatedName : "+jsonArray.getJSONObject(i).getString("formatedName"));
}
}else{
Toast.makeText(this,responeJson.getString("error_message"),Toast.LENGTH_SHORT).show();
}
}catch (Throwable e){
e.printStackTrace();
}
Related
JSON getting automatically sorted based on keys for the output of the REST API
I have a simple rest API written in java springboot that produces the JSON output as shown in the following example: { "status": 0, "data": { "total": 351, "offset": 0, "limit": 10, "info": { "1010": { "id": 1010, "name": "John", "age": 28 }, "1009": { "id": 1009, "name": "Philippe", "age": 42 }, "1008": { "id": 1008, "name": "Nick", "age": 22 }, "1007": { "id": 1007, "name": "Razor", "age": 19 }, "1006": { "id": 1006, "name": "Marco", "age": 67 }, "1005": { "id": 1005, "name": "Pablo", "age": 19 }, "1004": { "id": 1004, "name": "Sheldon", "age": 29 }, "1003": { "id": 1003, "name": "Hazel", "age": 34 }, "1002": { "id": 1002, "name": "Penny", "age": 44 }, "1001": { "id": 1001, "name": "Chris", "age": 41 } } }, "timeStamp": "2021-05-26T15:13:41.022+0000 UTC" } When I test the API using swagger, the JSON gets sorted automatically based on the keys in the following way: { "status": 0, "data": { "total": 351, "offset": 0, "limit": 10, "info": { "1001": { "id": 1001, "name": "Chris", "age": 41 }, "1002": { "id": 1002, "name": "Penny", "age": 44 }, "1003": { "id": 1003, "name": "Hazel", "age": 34 }, "1004": { "id": 1004, "name": "Sheldon", "age": 29 }, "1005": { "id": 1005, "name": "Pablo", "age": 19 }, "1006": { "id": 1006, "name": "Marco", "age": 67 }, "1007": { "id": 1007, "name": "Razor", "age": 19 }, "1008": { "id": 1008, "name": "Nick", "age": 22 }, "1009": { "id": 1009, "name": "Philippe", "age": 42 }, "1010": { "id": 1010, "name": "John", "age": 28 } } }, "timeStamp": "2021-05-26T15:13:41.022+0000 UTC" } Also when I use an online JSON viewer to visualize the JSON output, the behavior remains the same. However, when I hit the API using Postman, the order is retained. Can some explain this behavior and how this can be controlled?
Probably just a Swagger feature. See https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/ For readability, parameters are grouped by category and sorted alphabetically.
How to download saved reports using Fortify Software Security Center REST API?
I am trying to implement REST API for Fortify Software Security Center using Java. I am able to obtain 1)token by using following url http://xxx.xxx.xxx.xxx:8080/ssc/api/v1/auth/obtain_token response for above URL as below { "data": { "token": "NDIxMjE0NjUtOGIwNy00ZjFiLWEzMTUtZjZkYTg0MWY1Zjgz", "creationDate": "2016-09-14T05:49:34.000+0000", "terminalDate": "2016-09-15T05:49:34.000+0000" }, "responseCode": 200 } and 2)get list of reports using following URL http://xxx.xxx.xxx.xxx:8080/ssc/api/v1/reports response for above URL as below { "data": [ { "note": "", "_href": "http://xxx.xxx.xxx.xxx:8080/ssc/api/v1/reports/17", "formatDefaultText": "PDF", "projects": [ { "id": 16, "name": "Project 1", "versions": [ { "id": 30, "name": "1.0", "developmentPhase": "New" } ] } ], "authEntity": { "id": 2, "userName": "AAA", "firstName": "AAA", "lastName": "AAA" }, "isPublished": false, "format": "PDF", "generationDate": "2016-08-03T10:56:46.000+0000", "statusDefaultText": "Processing Complete", "reportDefinitionId": null, "type": "ISSUE", "typeDefaultText": "Issue Reports", "inputReportParameters": null, "name": "Project 1", "id": 17, "status": "PROCESS_COMPLETE" }, { "note": "", "_href": "http://xxx.xxx.xxx.xxx:8080/ssc/api/v1/reports/22", "formatDefaultText": "PDF", "projects": [ { "id": 16, "name": "Project 2", "versions": [ { "id": 30, "name": "1.0", "developmentPhase": "New" } ] } ], "authEntity": { "id": 10, "userName": "BBB", "firstName": "BBB", "lastName": "BBB" }, "isPublished": false, "format": "PDF", "generationDate": "2016-08-24T13:45:30.000+0000", "statusDefaultText": "Processing Complete", "reportDefinitionId": null, "type": "ISSUE", "typeDefaultText": "Issue Reports", "inputReportParameters": null, "name": "Project 2", "id": 22, "status": "PROCESS_COMPLETE" }, { "note": "", "_href": "http://xxx.xxx.xxx.xxx:8080/ssc/api/v1/reports/41", "formatDefaultText": "PDF", "projects": [ { "id": 2, "name": "Project 3", "versions": [ { "id": 3, "name": "1.0", "developmentPhase": "Active Development" } ] } ], "authEntity": { "id": 10, "userName": "CCC", "firstName": "CCC", "lastName": "CCC" }, "isPublished": false, "format": "PDF", "generationDate": "2016-08-25T16:56:22.000+0000", "statusDefaultText": "Processing Complete", "reportDefinitionId": null, "type": "ISSUE", "typeDefaultText": "Issue Reports", "inputReportParameters": null, "name": "Project 3", "id": 41, "status": "PROCESS_COMPLETE" }, { "note": "", "_href": "http://xxx.xxx.xxx.xxx:8080/ssc/api/v1/reports/57", "formatDefaultText": "XLS", "projects": [ { "id": 2, "name": "Project 4", "versions": [ { "id": 3, "name": "1.0", "developmentPhase": "Active Development" } ] } ], "authEntity": { "id": 11, "userName": "DDD", "firstName": "DDD", "lastName": "DDD" }, "isPublished": false, "format": "XLS", "generationDate": "2016-09-09T15:46:22.000+0000", "statusDefaultText": "Processing Complete", "reportDefinitionId": null, "type": "ISSUE", "typeDefaultText": "Issue Reports", "inputReportParameters": null, "name": "Project 4", "id": 57, "status": "PROCESS_COMPLETE" } ], "count": 4, "responseCode": 200, "links": { "last": { "href": "http://xxx.xxx.xxx.xxx:8080/ssc/api/v1/reports/?start=0" }, "first": { "href": "http://xxx.xxx.xxx.xxx:8080/ssc/api/v1/reports/?start=0" } } } But I didn't find any end point URL to download the saved reports. Can you please help me to get the end point URL or provide reference API document for HP fortify Software Security Center.
I know this is kind of an old post but just ran into the issue myself and found the solution. First you have to request a file token as a HTTPPost: http://xxx.xxx.xxx.xxx:8080/ssc/api/v1/fileTokens with: {"fileTokenType": "REPORT_FILE"} in the request body. This will return a unique id that you will use to fetch your report. Next you will make another get request like such: http://xxx.xxx.xxx.xxx:8080/ssc/transfer/reportDownload.html?mat=[file_token]&id=[project_id] you will replace the [file_token] with the token returned from the above post and [project_id] with the project you want to download the report for. so for example: http://xxx.xxx.xxx.xxx:8080/ssc/transfer/reportDownload.html?mat=7e8d912e-2432-6496-3232-709b05513bf2&id=1 This will return the binary data that you can then save to a file. The file type is specified in the report data as "format"
json value returning null when sent with ajax request
I am trying to send json string to server and then store it in db Following is my code: $.ajax({ url: 'JsonProcessor.do', type: 'post', dataType: 'json', data: { loadProds: 1, test: JSON.stringify(StateObject) }, success: function (data) { console.log("worked"); }, error: function (data) { alert('failed'); } }); Servlet: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String json = request.getParameter("test"); System.out.println("json is: " + json); Connection con = null; ResultSet rs = null; try { con = OracleDBConnection.getConnection(); String query = "insert into JJS (JSON_INFO) values(?)"; PreparedStatement pst = con.prepareStatement(query); pst.setString(1, json); rs = pst.executeQuery(); if (rs.next()) { System.out.println("sucess"); } else { System.out.println("failed"); } } catch (Exception e) { e.printStackTrace(); System.out.println("DB releated exception"); } However, when I try to print request.getparameter(json) it returns null. This is json I am trying to send: { "cells": [ { "type": "basic.Rect", "position": { "x": -2, "y": 33 }, "size": { "width": 71, "height": 625 }, "angle": 0, "isInteractive": false, "id": "e276b993-af5e-4e32-9879-fc3d817c0811", "z": 1, "attrs": { "rect": { "fill": "#EEEEEE", "stroke": "#008B8B", "stroke-width": 2 }, ".": { "magnet": false } } }, { "type": "basic.Rect", "position": { "x": 10, "y": 50 }, "size": { "width": 51, "height": 41 }, "angle": 0, "isInteractive": false, "id": "f8826904-678c-4857-ad46-f86e69d1db32", "z": 2, "attrs": { "rect": { "fill": "#D6F2FC", "stroke": "#7E7E7E" }, ".": { "magnet": false } } }, { "type": "basic.Circle", "size": { "width": 53, "height": 53 }, "position": { "x": 8, "y": 130 }, "angle": 0, "isInteractive": false, "id": "e4ee7b74-3c06-4e1e-8ce7-8baf6743c27c", "z": 3, "attrs": { ".": { "magnet": false }, "circle1": { "fill": "white", "stroke-width": 2, "stroke": "green" } } }, { "type": "basic.Circle", "size": { "width": 53, "height": 53 }, "position": { "x": 8, "y": 225 }, "angle": 0, "isInteractive": false, "id": "04d4a40b-f99b-4c16-89a9-7d072e30c4ad", "z": 4, "attrs": { ".": { "magnet": false }, "circle2": { "fill": "white", "stroke": "green" } } }, { "type": "basic.Circle", "size": { "width": 53, "height": 53 }, "position": { "x": 8, "y": 320 }, "angle": 0, "isInteractive": false, "id": "97a01219-b7e2-4a52-9248-eb41dc7443b4", "z": 5, "attrs": { ".": { "magnet": false }, "circle3": { "fill": "white", "stroke": "green" } } }, { "type": "basic.Rect", "position": { "x": 10, "y": 420 }, "size": { "width": 51, "height": 41 }, "angle": 0, "isInteractive": false, "id": "ed74bfd7-c7e2-4f68-85c3-0f1865243d3e", "z": 6, "attrs": { ".": { "magnet": false }, "rectGroup0": { "fill": "white", "stroke": "#7E7E7E" } } }, { "type": "basic.Rect", "position": { "x": 35, "y": 505 }, "size": { "width": 45, "height": 45 }, "angle": 0, "isInteractive": false, "id": "008c90ea-2598-4761-8775-fc3601c8935d", "z": 7, "attrs": { "rect": { "fill": "#FFED6B", "stroke": "#DBCB62", "width": 1, "height": 1, "stroke-width": 1, "transform": "rotate(45)" }, ".": { "magnet": false } } } ] }
There are multiple issues with your code: When sending, jquery already does the stringify for you, so you when calling it yourself you are actually creating a string attribute in the json sent (you can check this out easily by watching the data sent using your browser) $.ajax({ url: 'JsonProcessor.do', type: 'post', dataType: 'json', data: { loadProds: 1, test: JSON.stringify(StateObject) }, ... will actually create a http request body that looks like: { loadProds: 1, test: "{\"state\": .... " } so just write: $.ajax({ url: 'JsonProcessor.do', type: 'post', dataType: 'json', data: { loadProds: 1, test: StateObject }, ... and you will be fine on that part. As for the server part, you are actually looking for a request parameter named "test". But this is not what is being sent. Instead, you are getting a "body" that includes a json. there simply are no standard request parameter when using dataType:json. so in your case it is String json = IOUtils.toString(request.getInputStream()); Also not that the json you retrieve there includes the "loadProps: 1"... You then might want to convert the string into an object (using i.e. jackson) so you can work with it.
Dropwizard 8.0.1 PUT returns 400
I'm getting a 400 Error on calling put on a resource :"code":400,"message":"Unable to process JSON". I'm using the embedded jetty server I'm using postman as client for testing. Here is the method in the resource for put method: #Path("/Ads") public class AdResource { #PUT #Consumes(MediaType.WILDCARD) #Produces(MediaType.APPLICATION_JSON) #Timed #UnitOfWork public Response update(#Valid AdDTO adDto) { Ad ad = adDto.buildAd(); ad = adDao.merge(ad); return Response.ok(toJson(ad)).build(); } } Here is the Json data sent from the client: { "id": 44, "created": 1430927007000, "updated": 1430927052000, "category": "Voiture", "type": "Berline", "make": "AUDI", "model": "A3", "month": null, "year": 2002, "trimVersion": null, "transmission": "Manuelle", "fuel": "Diesel", "door": "4 portes", "color": "#FC809B", "metal": true, "warranty": true, "publish": false, "price": 123, "mileage": 123, "power": 123, "description": "<p>df sdfds sdfsdf sdfsdfds sdfsdfsd</p>", "adImages": [ { "id": 55, "created": 1430926983000, "updated": 1430926983000, "name": "amine.png", "url": "http://localhost/assets/photo/55/photo.png", "photoUrl": "http://localhost/assets/ad/44/55.jpg", "thumbPhotoUrl": "http://localhost/assets/ad/44/55_thumb.jpg" }, { "id": 54, "created": 1430926982000, "updated": 1430926982000, "name": "amine2.jpg", "url": "http://localhost/assets/photo/54/photo.jpg", "photoUrl": "http://localhost/assets/ad/44/54.jpg", "thumbPhotoUrl": "http://localhost/assets/ad/44/54_thumb.jpg" } ], "options": [ "1", "2", "13", "3", "14", "15" ] } The post and get methods works just fine. I'm using dropwizard 8.0.1 java 8.
Adding getters to all the variables of returned class solved the error for me.
Parsing JSON data in java from Facebook Graph response
Here I have a response from the facebook server that returns the list of albums of a selected user. I want to create an array for all the album names labeled "name" as well as the "link" and "cover_photo" to be ready to processed into a listview { "data": [ { "id": "664462156031", "from": { "name": "Nate Ellender", "id": "68004222" }, "name": "Mobile Uploads", "link": "https://www.facebook.com/album.php?fbid=664462156031&id=68004222&aid=2081375", "cover_photo": "754991180141", "count": 88, "type": "mobile", "created_time": "2012-05-12T00:38:14+0000", "updated_time": "2013-11-04T20:45:08+0000", "can_upload": false }, { "id": "813288706431", "from": { "name": "Nate Ellender", "id": "68004222" }, "name": "Bitstrips Photos", "link": "https://www.facebook.com/album.php?fbid=813288706431&id=68004222&aid=1073741826", "cover_photo": "813288781281", "count": 1, "type": "app", "created_time": "2013-10-31T21:53:11+0000", "updated_time": "2013-10-31T21:53:15+0000", "can_upload": false }, { "id": "757384214481", "from": { "name": "Nate Ellender", "id": "68004222" }, "name": "Galveston Vacation 2013", "description": "Our trip before joining Air Force", "link": "https://www.facebook.com/album.php?fbid=757384214481&id=68004222&aid=1073741825", "cover_photo": "757221350861", "count": 8, "type": "normal", "created_time": "2013-05-15T18:37:19+0000", "updated_time": "2013-05-15T22:12:52+0000", "can_upload": false, "likes": { "data": [ { "id": "100002572634186", "name": "Misty O'Quain" }, { "id": "100000582072776", "name": "Clifford Joyce" }, { "id": "1045514613", "name": "Caity Ellender" } ], "paging": { "cursors": { "after": "MTA0NTUxNDYxMw==", "before": "MTAwMDAyNTcyNjM0MTg2" } } } }, { "id": "542202136091", "from": { "name": "Nate Ellender", "id": "68004222" }, "name": "Profile Pictures", "link": "https://www.facebook.com/album.php?fbid=542202136091&id=68004222&aid=2054735", "cover_photo": "749743202131", "count": 20, "type": "profile", "created_time": "2010-09-02T04:43:32+0000", "updated_time": "2013-04-13T13:46:14+0000", "can_upload": false }, { "id": "646032913381", "from": { "name": "Nate Ellender", "id": "68004222" }, "name": "Cover Photos", "link": "https://www.facebook.com/album.php?fbid=646032913381&id=68004222&aid=2079483", "cover_photo": "681058471881", "count": 2, "type": "cover", "created_time": "2012-03-22T00:25:50+0000", "updated_time": "2012-07-17T15:26:24+0000", "can_upload": false }, { "id": "599115930391", "from": { "name": "Nate Ellender", "id": "68004222" }, "name": "Timeline Photos", "link": "https://www.facebook.com/album.php?fbid=599115930391&id=68004222&aid=2073818", "cover_photo": "599115935381", "count": 1, "type": "wall", "created_time": "2011-10-20T14:25:23+0000", "updated_time": "2011-10-20T14:25:23+0000", "can_upload": false }, { "id": "551798524851", "from": { "name": "Nate Ellender", "id": "68004222" }, "name": "My Year - 2010", "link": "https://www.facebook.com/album.php?fbid=551798524851&id=68004222&aid=2060899", "cover_photo": "551798544811", "count": 1, "type": "normal", "created_time": "2010-12-19T05:11:51+0000", "updated_time": "2010-12-19T05:12:14+0000", "can_upload": false }, { "id": "522841060841", "from": { "name": "Nate Ellender", "id": "68004222" }, "name": "Night Lightnin", "description": "Always wanted to do this, because lightning is way cooler at night. Perhaps next time I'll be able to refine my methods a little. Read as \"bring tripod so you don't have to prop cam up on roof of car\"", "location": "Just north of Sulphur", "link": "https://www.facebook.com/album.php?fbid=522841060841&id=68004222&aid=2036447", "cover_photo": "522841195571", "count": 15, "type": "normal", "created_time": "2009-09-16T04:38:43+0000", "updated_time": "2009-09-16T04:42:32+0000", "can_upload": false }, { "id": "513270939441", "from": { "name": "Nate Ellender", "id": "68004222" }, "name": "The Stuff That Doesn't Make Another Album", "description": "See title.", "location": "Good question", "link": "https://www.facebook.com/album.php?fbid=513270939441&id=68004222&aid=2029083", "cover_photo": "513271029261", "count": 9, "type": "normal", "created_time": "2009-03-03T06:43:09+0000", "updated_time": "2009-04-01T02:20:22+0000", "can_upload": false, "comments": { "data": [ { "id": "513270939441_3444", "from": { "name": "Misty Bylsma Royal", "id": "592607110" }, "message": "I love how the beautiful lady pile is in the same album as the bull pics. Nice.", "can_remove": false, "created_time": "2009-03-03T22:37:18+0000", "like_count": 0, "user_likes": false }, { "id": "513270939441_3451", "from": { "name": "Nate Ellender", "id": "68004222" }, "message": "Only because they are both things that i only had a few pictures of.", "can_remove": false, "created_time": "2009-03-04T02:46:11+0000", "like_count": 0, "user_likes": false } ], "paging": { "cursors": { "after": "Mg==", "before": "MQ==" } } } }, { "id": "511605661671", "from": { "name": "Nate Ellender", "id": "68004222" }, "name": "What the...?", "description": "What's wrong with the rain? It's flaky and piles up on stuff... Did the plants leak something?\n", "location": "Outside", "link": "https://www.facebook.com/album.php?fbid=511605661671&id=68004222&aid=2026641", "cover_photo": "511605681631", "count": 54, "type": "normal", "created_time": "2008-12-11T11:59:27+0000", "updated_time": "2008-12-13T18:06:00+0000", "can_upload": false }, { "id": "511565886381", "from": { "name": "Nate Ellender", "id": "68004222" }, "name": "The Christmas Tree Farm", "description": "An Ellender Tradition", "location": "Grant", "link": "https://www.facebook.com/album.php?fbid=511565886381&id=68004222&aid=2026590", "cover_photo": "511566170811", "count": 19, "type": "normal", "created_time": "2008-12-09T02:38:54+0000", "updated_time": "2008-12-09T02:55:21+0000", "can_upload": false } ], "paging": { "cursors": { "after": "NTExNTY1ODg2Mzgx", "before": "NjY0NDYyMTU2MDMx" } } } Also, here is where the json data is returned (response). I will need to start parsing the data under response. Session.NewPermissionsRequest np = new Session.NewPermissionsRequest(this, "friends_photos"); Session.getActiveSession().requestNewReadPermissions(np); Request rq = new Request(Session.getActiveSession(), userID + "/albums", null, HttpMethod.GET, new Request.Callback() { #Override public void onCompleted(Response response) { } }); rq.executeAsync(); Any example would be helpful. I would like to study the code to get a better understanding on parsing json data.
You can get a good example of how to do here: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ Basically you have to use JSONObject and JSONArray, that you can get from getJSONObject() and getJSONArray(). Once you're on the good spot, use getJSONString() to get the desired value. In your case it will be something like this: JSONObject json = new JSONObject(response) JSONArray jarray = json.getJSONArray("data"); for(int i = 0; i < jarray.length(); i++){ JSONObject oneAlbum = jarray.getJSONObject(i); //get your values oneAlbum.getJSONString("name"); // this will return you the album's name. } Hope this will help you.
Try this Session.NewPermissionsRequest np = new Session.NewPermissionsRequest(this, "friends_photos"); Session.getActiveSession().requestNewReadPermissions(np); Request rq = new Request(Session.getActiveSession(), userID + "/albums", null, HttpMethod.GET, new Request.Callback() { #Override public void onCompleted(Response response) { JSONArray albumArr = response.getGraphObject().getInnerJSONObject().getJSONArray("data"); for (int i = 0; i < albumArr.length(); i++) { JSONObject item = albumArr.getJSONObject(i); System.out.println("id : " + item.getString("id")); System.out.println("fromName : " + item.getJSONObject("from").getString("name")); System.out.println("fromid : " + item.getJSONObject("from").getString("id")); System.out.println("link : " + item.getString("link")); System.out.println("cover_photo : " + item.getString("cover_photo")); System.out.println("count : " + item.getString("count")); System.out.println("created_time : " + item.getString("created_time")); System.out.println("updated_time : " + item.getString("updated_time")); System.out.println("can_upload : " + item.getString("can_upload")); } } }); rq.executeAsync();