Telemetry Collector not logging/exporting http calls - java

I am using Opentelemetry collector with below configuration which uses http receiver and export it to logs but when I call the API it returns 200 http code but in the console of collector I don't see any logs.
NOTE: I am using otel/opentelemetry-collector-contrib:0.68.0 Image
collector-config.yaml
receivers:
otlp:
protocols:
http: http://localhost:4318
exporters:
logging:
loglevel: debug
service:
pipelines:
traces:
exporters: [logging]
receivers: [otlp]
metrics:
exporters: [logging]
receivers: [otlp]
logs:
exporters: [logging]
receivers: [otlp]
telemetry:
metrics:
level: detailed
Http Call:
POST: http://localhost:4318/v1/metrics
Request Body
{
"resourceMetrics_": [
{
"resource_": {
"attributes_": [
{
"key_": "loki.attribute.labels",
"value_": {
"valueCase_": 1,
"value_": "http.status",
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
},
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
},
{
"key_": "loki.resource.labels",
"value_": {
"valueCase_": 1,
"value_": "host.name, pod.name",
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
},
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
}
],
"droppedAttributesCount_": 0,
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
},
"scopeMetrics_": [
{
"scope_": {
"name_": "otelcol/hostmetricsreceiver/load",
"version_": "0.68.0",
"attributes_": [],
"droppedAttributesCount_": 0,
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
},
"metrics_": [
{
"dataCase_": 5,
"data_": {
"dataPoints_": [
{
"valueCase_": 4,
"value_": 0.94,
"attributes_": [
{
"key_": "loki.attribute.labels",
"value_": {
"valueCase_": 1,
"value_": "http.status_code",
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
},
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
}
],
"startTimeUnixNano_": 1673933623000000000,
"timeUnixNano_": 1673962743472355755,
"exemplars_": [],
"flags_": 0,
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
}
],
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
},
"name_": "system.cpu.load_average.15m",
"description_": "Average CPU Load over 15 minutes.",
"unit_": "1",
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
},
{
"dataCase_": 5,
"data_": {
"dataPoints_": [
{
"valueCase_": 4,
"value_": 0.99,
"attributes_": [
{
"key_": "loki.attribute.labels",
"value_": {
"valueCase_": 1,
"value_": "http.status_code",
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
},
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
}
],
"startTimeUnixNano_": 1673933623000000000,
"timeUnixNano_": 1673962743472355755,
"exemplars_": [],
"flags_": 0,
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
}
],
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
},
"name_": "system.cpu.load_average.1m",
"description_": "Average CPU Load over 1 minute.",
"unit_": "1",
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
},
{
"dataCase_": 5,
"data_": {
"dataPoints_": [
{
"valueCase_": 4,
"value_": 0.81,
"attributes_": [
{
"key_": "loki.attribute.labels",
"value_": {
"valueCase_": 1,
"value_": "http.status_code",
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
},
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
}
],
"startTimeUnixNano_": 1673933623000000000,
"timeUnixNano_": 1673962743472355755,
"exemplars_": [],
"flags_": 0,
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
}
],
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
},
"name_": "system.cpu.load_average.5m",
"description_": "Average CPU Load over 5 minutes.",
"unit_": "1",
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
}
],
"schemaUrl_": "",
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
}
],
"schemaUrl_": "https://opentelemetry.io/schemas/1.9.0",
"memoizedIsInitialized": -1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
}
],
"memoizedIsInitialized": 1,
"unknownFields": {
"fields": {}
},
"memoizedSize": -1,
"memoizedHashCode": 0
}
Collector Logs:

Use older OTLP collector version, which has older OTLP protocol version and you will get error response for your payload:
{
"code": 3,
"message": "unknown field \"unknownFields\" in v1.ExportMetricsServiceRequest"
}
Newer versions ignore unknowns fields silently, so you don't see any error.
Tested with public.ecr.aws/aws-observability/aws-otel-collector:v0.21.0

Related

hide default parameters of page from json response | spring boot | Netflix Eurekka

I have JSON response from spring boot as,
{
"content": [],
"pageable": {
"sort": {
"sorted": true,
"unsorted": false,
"empty": false
},
"offset": 0,
"pageNumber": 0,
"pageSize": 10,
"unpaged": false,
"paged": true
},
"totalPages": 0,
"totalElements": 0,
"last": true,
"size": 10,
"number": 0,
"sort": {
"sorted": true,
"unsorted": false,
"empty": false
},
"numberOfElements": 0,
"first": true,
"empty": true
}
But I need this response as below,
{
"content": [],
"last": true,
"totalPages": 0,
"totalElements": 0,
"size": 10,
"number": 0,
"sort": null,
"first": true,
"numberOfElements": 0
}
in brief, How can I modify the default parameters of returned response? is there any extra configuration I can set for that? thanks in advance
I guess you're using spring data page so just create an implementation of JsonSerializer
eg.
#JsonComponent
public class PageImplJacksonSerializer extends JsonSerializer<PageImpl> {
#Override
public void serialize(PageImpl page, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField("content", page.getContent());
jsonGenerator.writeBooleanField("first", page.isFirst());
jsonGenerator.writeBooleanField("last", page.isLast());
jsonGenerator.writeNumberField("page_number", page.getNumber());
jsonGenerator.writeNumberField("elements_per_page", page.getNumberOfElements());
jsonGenerator.writeNumberField("total_pages", page.getTotalPages());
jsonGenerator.writeNumberField("total_elements", page.getTotalElements());
jsonGenerator.writeEndObject();
}
}

Orika Object mapper not mapping Lists

I am using an object mapper called Orika, and I have some doubts regarding how it works or am I doing anything wrong here.
Following are the classes
https://googleapis.dev/java/google-cloud-channel/latest/com/google/cloud/channel/v1/Entitlement.html
This is the source class structure, an object comes in this format.
Entitlements.java
#Data
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Entitlement {
private String name;
private String createTime;
private String updateTime;
private String offer;
private String provisioningState;
private ProvisionedService provisionedService;
private String purchaseOrderId;
private List<String> suspensionReasons;
private CommitmentSettings commitmentSettings;
private TrialSettings trialSettings;
private AssociationInfo associationInfo;
private List<Parameter> parameters;
}
Parameter.java
#Data
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Parameter {
private String name;
private Value value;
private boolean editable;
}
My orika mapper code:
public class OrikaMapper {
private MapperFactory mapperFactory;
public <S, D> D map(S s, Class<D> type) {
return this.mapperFactory.getMapperFacade().map(s, type);
}
}
my method:
public Entitlement getEntitlement(String credential, String customerId, String entitlementId) {
CloudChannelServiceClient client = null;
Entitlement resp = null;
try {
client = <<>>;
String name = "accounts/"+ ACCOUNT_ID +"/customers/"+customerId+"/entitlements/"+entitlementId;
GetEntitlementRequest request = GetEntitlementRequest.newBuilder().setName(name).build();
com.google.cloud.channel.v1.Entitlement entitlement = client.getEntitlement(request);
resp = orikaMapper.map(gson.toJson(entitlement), Entitlement.class);
} catch (Exception e) {
throw new ApplicationException("code", e.getMessage());
}
return resp;
}
sample response from google API
{ "name_": "<<>>", "createTime_": { "seconds_": 1615715413, "nanos_": 810000000, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "offer_": "<<>>", "provisioningState_": 5, "provisionedService_": { "provisioningId_": "<<>>", "productId_": "<<>>", "skuId_": "<<>>", "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "suspensionReasons_": [ 4 ], "suspensionReasonsMemoizedSerializedSize": 0, "purchaseOrderId_": "A codelab test", "trialSettings_": { "trial_": false, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "parameters_": [ { "name_": "max_units", "value_": { "kindCase_": 1, "kind_": 4, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "editable_": true, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, { "name_": "assigned_units", "value_": { "kindCase_": 1, "kind_": 1, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "editable_": false, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 } ], "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }
Response after mapping in orika
{ "name": "<<>>", "createTime": "seconds: 1615715413\nnanos: 810000000\n", "updateTime": "", "offer": "<<>>", "provisioningState": "SUSPENDED", "provisionedService": { "provisioningId": "<<>>", "productId": "<<>>", "skuId": "<<>>" }, "purchaseOrderId": "A codelab test", "commitmentSettings": { "startTime": "", "endTime": "", "renewalSettings": { "enableRenewal": false, "resizeUnitCount": false, "paymentPlan": "PAYMENT_PLAN_UNSPECIFIED", "paymentCycle": { "duration": 0, "periodType": "PERIOD_TYPE_UNSPECIFIED" } } }, "trialSettings": { "trial": false, "endTime": "" }, "associationInfo": { "baseEntitlement": "" } }
My issue is, the response is not able to map what is in the List<> fields. All the other fields are mapped.
What am i missing here.
Rather late in reply, but if this helps anyone in the future. I was facing the same issue. It seems that you have to explicitly call:
mapper.mapAsList
I.e. in questioner's case:
parameters = orikaMapper.mapAsList(entitlement.getParameters(), Parameter.class);

Limiting Bucket Size Returned By Aggregation

I have a huge amount of elasticsearch data, I neeed to make aggregations and return buckets. I need to limit data size returned from elasticsearch to only get a sample for the data not all data.
I have tried adding "size" attribute. But it's not acceptable in bucketing aggregations.
{
"size": 0,
"query": {
"bool": {
"adjust_pure_negative": true,
"boost": 1
}
},
"aggregations": {
"my_agg_1": {
"histogram": {
"field": "coAt",
"interval": 86400,
"offset": 1558216800,
"order": {
"_key": "asc"
},
"keyed": false,
"min_doc_count": 1
},
"aggregations": {
"my_agg_2": {
"terms": {
"field": "atr1",
"missing": "NaN",
"value_type": "string",
"size": 2147483647,
"min_doc_count": 1,
"shard_min_doc_count": 0,
"show_term_doc_count_error": false,
"order": [
{
"_count": "desc"
},
{
"_key": "asc"
}
]
},
"aggregations": {
"atr2": {
"top_hits": {
"from": 0,
"size": 1,
"version": false,
"explain": false,
"sort": [
{
"coAt": {
"order": "desc"
}
}
]
}
},
"clientIP_count": {
"value_count": {
"field": "clientIP"
}
}
}
}
}
}
}
}

Java - Magento2 rest api product upload with image silently fails

I have a magento CE 2.1.2 storefront set up. I'd like to use Java to upload products to my store using the Magento REST API. I have managed to get 2 leg OAuth set up using Apache-commons-httpclient, and product upload actually works quite well. The problem comes when I try to upload an image with the product.
From the official catalogProductRepositoryV1 Magento docs, the json syntax is: (the important part being the "media_gallery_entries" bit)
{
"product": {
"id": 0,
"sku": "string",
"name": "string",
"attribute_set_id": 0,
"price": 0,
"status": 0,
"visibility": 0,
"type_id": "string",
"created_at": "string",
"updated_at": "string",
"weight": 0,
"extension_attributes": {
"bundle_product_options": [
{
"option_id": 0,
"title": "string",
"required": true,
"type": "string",
"position": 0,
"sku": "string",
"product_links": [
{
"id": "string",
"sku": "string",
"option_id": 0,
"qty": 0,
"position": 0,
"is_default": true,
"price": 0,
"price_type": 0,
"can_change_quantity": 0,
"extension_attributes": {}
}
],
"extension_attributes": {}
}
],
"downloadable_product_links": [
{
"id": 0,
"title": "string",
"sort_order": 0,
"is_shareable": 0,
"price": 0,
"number_of_downloads": 0,
"link_type": "string",
"link_file": "string",
"link_file_content": {
"file_data": "string",
"name": "string",
"extension_attributes": {}
},
"link_url": "string",
"sample_type": "string",
"sample_file": "string",
"sample_file_content": {
"file_data": "string",
"name": "string",
"extension_attributes": {}
},
"sample_url": "string",
"extension_attributes": {}
}
],
"downloadable_product_samples": [
{
"id": 0,
"title": "string",
"sort_order": 0,
"sample_type": "string",
"sample_file": "string",
"sample_file_content": {
"file_data": "string",
"name": "string",
"extension_attributes": {}
},
"sample_url": "string",
"extension_attributes": {}
}
],
"stock_item": {
"item_id": 0,
"product_id": 0,
"stock_id": 0,
"qty": 0,
"is_in_stock": true,
"is_qty_decimal": true,
"show_default_notification_message": true,
"use_config_min_qty": true,
"min_qty": 0,
"use_config_min_sale_qty": 0,
"min_sale_qty": 0,
"use_config_max_sale_qty": true,
"max_sale_qty": 0,
"use_config_backorders": true,
"backorders": 0,
"use_config_notify_stock_qty": true,
"notify_stock_qty": 0,
"use_config_qty_increments": true,
"qty_increments": 0,
"use_config_enable_qty_inc": true,
"enable_qty_increments": true,
"use_config_manage_stock": true,
"manage_stock": true,
"low_stock_date": "string",
"is_decimal_divided": true,
"stock_status_changed_auto": 0,
"extension_attributes": {}
},
"configurable_product_options": [
{
"id": 0,
"attribute_id": "string",
"label": "string",
"position": 0,
"is_use_default": true,
"values": [
{
"value_index": 0,
"extension_attributes": {}
}
],
"extension_attributes": {},
"product_id": 0
}
],
"configurable_product_links": [
0
]
},
"product_links": [
{
"sku": "string",
"link_type": "string",
"linked_product_sku": "string",
"linked_product_type": "string",
"position": 0,
"extension_attributes": {
"qty": 0
}
}
],
"options": [
{
"product_sku": "string",
"option_id": 0,
"title": "string",
"type": "string",
"sort_order": 0,
"is_require": true,
"price": 0,
"price_type": "string",
"sku": "string",
"file_extension": "string",
"max_characters": 0,
"image_size_x": 0,
"image_size_y": 0,
"values": [
{
"title": "string",
"sort_order": 0,
"price": 0,
"price_type": "string",
"sku": "string",
"option_type_id": 0
}
],
"extension_attributes": {}
}
],
"media_gallery_entries": [
{
"id": 0,
"media_type": "string",
"label": "string",
"position": 0,
"disabled": true,
"types": [
"string"
],
"file": "string",
"content": {
"base64_encoded_data": "string",
"type": "string",
"name": "string"
},
"extension_attributes": {
"video_content": {
"media_type": "string",
"video_provider": "string",
"video_url": "string",
"video_title": "string",
"video_description": "string",
"video_metadata": "string"
}
}
}
],
"tier_prices": [
{
"customer_group_id": 0,
"qty": 0,
"value": 0,
"extension_attributes": {}
}
],
"custom_attributes": [
{
"attribute_code": "string",
"value": "string"
}
]
},
"saveOptions": true
}
The methods I'm running:
public void uploadItem(ItemType item) throws UploadException {
try {
HttpPost postRequest = new HttpPost("http://my.magento.storefront/index.php/rest/V1/products");
postRequest.addHeader("Content-Type", "application/json");
postRequest.addHeader("Authorization", String.format("Bearer %s", authToken));
String jsonItem = itemToJson(item);
System.out.println(jsonItem);
postRequest.setEntity(new StringEntity(jsonItem));
HttpResponse postResponse = httpClient.execute(postRequest);
System.out.println();
System.out.println(EntityUtils.toString(postResponse.getEntity()));
} catch (ParseException | IOException | JSONException e) {
e.printStackTrace();
throw new UploadException(e);
}
}
private String imagesToJson(ItemType item) throws IOException {
String imageUrl = "http://my.image.jpeg"; //pulled from item in production
String encodedImage = null;
URL url = new URL(imageUrl);
try(InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
byte[] buf = new byte[512];
for (int count = in.read(buf); count >= 0; count = in.read(buf)) {
out.write(buf, 0, count);
}
byte[] response = out.toByteArray(); //sane, I tried saving to a file and checking
encodedImage = Base64.getEncoder().encodeToString(response);
}
String picName = item.getItemID() + ".jpg";
return new JSONArray().put(
new JSONObject()
.put("position", 0)
.put("media_type", "image")
.put("disabled", "false")
.put("types", new JSONArray()
.put("image")
.put("small_image")
.put("thumbnail"))
.put("label", picName)
.put("content", new JSONObject()
.put("base64_encoded_data", encodedImage)
.put("type", "image/jpeg")
.put("name", picName))
).toString();
}
private String itemToJson(ItemType item) throws JSONException, IOException {
return new JSONObject().put("saveOptions", "true").put("product",
new JSONObject()
.put("sku", item.getItemID())
.put("name", item.getTitle())
.put("attribute_set_id", 4)
.put("price", item.getSellingStatus().getCurrentPrice().getValue())
.put("status", 0)
.put("visibility", 0)
.put("type_id", "simple")
.put("weight", item.getShippingDetails().getCalculatedShippingRate().getWeightMajor().getValue())
.put("media_gallery_entries", imagesToJson(item)))
.toString();
}
Using uploadItem(ItemType), the product is uploaded to the catalog. However, there is no image on the store, and I'm given "media_gallery_entries": [] in the response, with no further debugging help!
I think I've implemented everything correctly, so I'm unsure what to do other than SFTP and manually manage the media folder; which just sounds ugly.
Let me know if anyone needs any extra info, or omitted methods/fields.
I solved this by using Gson instead of org.json. I believe the issue was me erroneously using string literals where the server expected otherwise (namely, the boolean values).

How to parse JSON results from Unirest call

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();
}

Categories