JSON file
[ { customerId:1}, { customerId:2 }, { customerId:3>} ]
in JAVA with
Response resp = when().get("link");
i received the json to resp file.
Now from the resp file - i'm tring to create a arrray - soo that all the values of the customerId is saved in that array using the below code
ArrayList list = resp
.then()
.contentType(ContentType.JSON)
.extract()
.path(".customerId");
but its not working.
can someone help me out.?
Related
So I am trying to create a simple webservice post that consumes json. But I am geting the error RESTEASY002010: Failed to execute: javax.ws.rs.NotSupportedException: RESTEASY003065: Cannot consume content type
My webservice:
#POST
#Produces(MediaType.APPLICATION_XML)
#Path("teste1")
#Consumes(MediaType.APPLICATION_JSON)
public Response teste1(String product) {
String result = "Product created : " + product;
System.out.println("resultado");
System.out.println(result);
return Response.ok() //200
.entity("<erro> none </erro>")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With").build();
}
I also tried to do:
#Consumes("application/json")
But I am getting the same error. I can make it work if I do:
#Consumes("*/*")
But I can't understand why it doesn't work when I say it consumes json. To test the webservice I am using https://apitester.com/. With the folowing Post Data:
{
"key" : "value",
"array" : [
{ "key" : 1 },
{ "key" : 2, "dictionary": {
"a": "Apple",
"b": "Butterfly",
"c": "Cat",
"d": "Dog"
} },
{ "key" : 3 }
]
}
In general the
#Consumes("application/json")
specifies a content media type which webservice can handle.
But also you may need to explicitly specify an appropriate type in the Content-Type header for your request.
I am not familiar with the https://apitester.com but probably it does not send the Content-Type header by default
In such case your server can treat the request body as a plain text, for instance. That request would not be routed to your endpoint, because it is not designed for the plain text.
Setting the #Consumes(*/*) fixes that problem, because the wrong media type matches that pattern as well.
Could you please ensure that you sends the Content-Type: application/json with your POST request?
I need to receive JSON data from this Api http://countryapi.gear.host/v1/Country/getCountries using REST API. I need to receive NativeName and Region for the specific country.
My main problem is how to send request for the specific country (for example I print Name Australia) and get the response for NativeName and Region - Australia, Oceania (it should be String).
I have such classes:
public class Client {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient clientGetEntity = new DefaultHttpClient();
HttpGet request = new HttpGet("http://countryapi.gear.host/v1/Country/getCountries?pName=Australia");
request.addHeader("accept", "application/json");
HttpResponse responseGetEntity = clientGetEntity.execute(request);
//String json =EntityUtils.toString((HttpEntity) responseGetEntity);
System.out.println("Request : " + request.toString());
System.out.println("Response : " + responseGetEntity.toString());
}
}
EDITS
As regards getting the specific country's name, you need to make a get request with the country name such as:
http://countryapi.gear.host/v1/Country/getCountries?pName=Australia
The response from this request:
{
"IsSuccess": true,
"UserMessage": null,
"TechnicalMessage": null,
"TotalCount": 1,
"Response": [
{
"Name": "Australia",
"Alpha2Code": "AU",
"Alpha3Code": "AUS",
"NativeName": "Australia",
"Region": "Oceania",
"SubRegion": "Australia and New Zealand",
"Latitude": "-27",
"Longitude": "133",
"Area": 7692024,
"NumericCode": 36,
"NativeLanguage": "eng",
"CurrencyCode": "AUD",
"CurrencyName": "Australian dollar",
"CurrencySymbol": "$",
"Flag": "https://api.backendless.com/2F26DFBF-433C-51CC-FF56-830CEA93BF00/473FB5A9-D20E-8D3E-FF01-E93D9D780A00/files/CountryFlags/aus.svg",
"FlagPng": "https://api.backendless.com/2F26DFBF-433C-51CC-FF56-830CEA93BF00/473FB5A9-D20E-8D3E-FF01-E93D9D780A00/files/CountryFlagsPng/aus.png"
}
]
}
You can access NativeName and region by:
data.Response[0].NativeName and data.Response[0].Region respectively.
Since the data returned from the API is always a JSON string, dont forget to parse the string before use.
----------------------------------------
I am not a java developer but I have dealt with a lot of JSON data, Also C# and TypeScript projects.
First, you should take a look at this line:
request.addHeader("accept", "application/fson");
Am afraid this is not a valid JSON request header and if we where to start debugging your code, it would be difficult to pinpoint where the problem lies if the basis of the whole request is faulty. Please correct to:
request.addHeader("accept", "application/json"); and try again, if you have the same result, we can continue debugging from there.
I am trying to get the URL from the following JSON response:
{
"json": {
"errors": [],
"data": {
"url": "urlIWant.com",
"id": "asdklfjads",
"name": "sdfjklsdf"
}
}
}
I have been banging my head against the wall trying to get the URL out of this response. What code do I need to access that url in Android?
Here is the latest few lines of code that I have tried to get the url.
JSONObject json = new JSONObject(responseStr);
json = json.getJSONObject("data"); //Get the "data" object out of the JSON
url = json.getString("url"); //Grab the URL from the object
Log.d("JSON URL", url); //url is null here
It looks like you should be grabbing from the "json" field first before you try to access "data".
You could use retrofit along with GSON to do the work for you.
There are some tutorials out there teaching how to use them.
1 liner:
new JSONObject(json).getJSONObject("json").getJSONObject("data").getString("url")
I am writing Junit test case for my REST service, i am setting the values(below is the piece of code) to get the payload required for REST service
Payload jsonPayload = new Payload ();
payload.setAcc("A");
List<Details> details= new ArrayList<Details>;
Details detail = new Details();
detail.setTotalAmount(1);
detail.setCurrency("dollar");
details.add(detail);
payload.getDetails().addAll(details);
I want JSON to be built in format mentioned below, but I am not getting the JSON as expected, details should be in form of Array.
Required JSON -
{
"Acc" : "A",
"details": [
{
"totalAmount":1,
"currency":"dollar"
}
]
}
Output JSON -
{
"Acc" : "A",
"details":
{
"totalAmount":1,
"currency":"dollar"
}
}
Can anyone help me how can I achieve this?
I have the json format like following
{
"items": [
{
"id": 0,
"name": "name1"
},
{
"id": 1,
"name": "name2"
}
]
}
I want to filter name from it , Array name = [name1, name2]
#GET (Web service)
#Produces(MediaType.APPLICATION_JSON)
public Response getItem() {
ClientConfig config = new ClientConfig();
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(getUserName(),getUserPassword());
config.register(feature);
Client client = ClientBuilder.newClient(config);
WebTarget service = client.target(getURI() + "/Item");
Response response = service.request().header("Content-Type", "application/json").get();
return response;
}
I have already tried here
http://gotoanswer.com/?q=How+to+Parse+the+this+JSON+Response+in+JAVA
then success.
But how can I do to dynamicaly get json format from Response to string
so that I can input to String jsonString.
When you are parsing your json, the 'items' is an array in your json. So if you try to get the 'items' you will need to type cast it to JSONArray. And iterating on this JSONArray you can get the values of the array using the attributes defined like 'name' and 'id'.
Can you try like this?
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray items = (JSONArray) jsonObject.get("items");
for (int 1 = 0; i < items.length(); i++)
{
System.out.println( items.get(i).get("name");
}
Hope it will help you.