Arraylist is coming as string in while sending in webservice - java

JSONObject myObject = new JSONObject();
try {
testVoList.add(new TestVO(1L, "HAI1"));
testVoList.add(new TestVO(2L, "HAI2"));
myObject.put("name", testVoList);
} catch (JSONException ex) {
}
String s = URLEncoder.encode(myObject.toString(), "UTF-8");
URL url = new URL("urlName/"+s);
CODE IN WEBSERVICE TO RECIEVE DATA:
#POST
#Path("/urlName/{test}")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String saveSurveyresponseData(#PathParam("test") JSONObject responseData)
{
JSONArray.fromObject(responseData.getString("name")).get(0);
return "HAI";
}
Here i am getting test.TestVO#c2ea3f(Hashcode) for
JSONArray.fromObject(responseData.getString("name")).get(0);
How can I access my list of objects values in my webservice.
Can you suggest me a solution?

I believe the following statement:
JSONArray.fromObject(responseData.getString("name")).get(0);
is returning the list. So simply assign it to a list reference as mentioned here:
List<TestVO> listOfTestVO = JSONArray.fromObject(responseData.getString("name")).get(0);
Now simply get the elements as:
listOfTestVO.get(1);

Related

Adding a new element to an array in the json object java

I am writing automation script to validate json responses of REST APIs and i am using faster xml to serialize and convert java object to json format.
I have a user case where I have to get the json response and add a new array element to an existing array and post it back.
The json response after GET looks like this :
{
"name":"test",
"id":"1234",
"nodes":[
{
"nodeId":"node1"
},
{
"nodeId":"node2"
}
]
}
To this json response, I need to add a third entry for nodes array
{ "nodeId": "node3" } and then post this.
Can someone please help me understand how to add a new array element to an existing array?
You can try:
//Your JSON response will be in this format
String response = "{ \"name\":\"test\", \"id\":\"1234\", \"nodes\":[ { \"nodeId\":\"node1\" }, { \"nodeId\":\"node2\" } ] }";
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray nodesArray = jsonResponse.getJSONArray("nodes");
JSONObject newEntry = new JSONObject();
newEntry.put("nodeId","node3");
nodesArray.put(newEntry);
jsonResponse.put("nodes",nodesArray);
} catch (JSONException e) {
e.printStackTrace();
}
Now you can post your jsonResponse.toString() as required.
I would rather go for cleaner approach, create Object with below structure -
public class Response{
private String name;
private int id;
private List<Node> nodes;
<Getter & Setter>
}
public class Node{
private String nodeId;
}
Serialize the json -
Response response = objectMapper.readValue(responseJson,
Response.class);
Add the new incoming node object to response -
response.getNodes().add(New Node("{new node Value}"));
Deserialize before post -
objectMapper.writeValueAsString(response);

Jersey Client returns HTTP 204 in a post method while trying to send jsonObject

Hey so I'm trying to send some json-object to a rest web service, then get the value of some specific keys, then process the data to finally return a new json-object which is going to be used in another place. Anyway, I'm getting HTTP 204 when I try to communicate with the service.
My rest service looks like this
#Path("/example")
public class PdfMaker {
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response PruebasMet(JSONObject json) throws IOException, JSONException{
try{
String xml = json.getString("xml");
String plantilla = json.getString("plant");
//method that uses "xml" and "plant" and returns "pdf"
JSONObject response = new JSONObject();
response.put("pdf", pdf);
return Response.status(200).entity(pdfb64.toString()).build();
}catch(Exception e){
e.getStackTrace();
return null;
}
}
and I'm trying to communicate with this
public class Jersey {
public static String baseuri = "http://localhost:8080/PdfMakerGF/rest/example/post";
public static void main(String[] args) {
try {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource(baseuri);
JSONObject objTest = new JSONobject();
objTest.put("xml","Data1");
objTest.put("plan", "Data2");
ClientResponse res = webResource.header("Content-Type","application/json;charset=UTF-8")
.post(ClientResponse.class, objTest.toString());
System.out.println("output..." + "\n");
System.out.println("Answer "+res);
} catch (Exception e) {
e.printStackTrace();
}
}
But the response that I receive is this one
Answer POST http://localhost:8080/PdfMakerGF/rest/example/post
returned a response status of 204 No Content
Obviously there is something wrong but can't see what is it.
Since I'm stuck with this. Any kind of help would be appreciated.
I'm using netbeans 8.1, Glassfish 4.1 and Jersey.
Thanks
If your server runs into an exception and goes to the catch block, it returns null which corresponds to HTTP 204 (No Content). As sisyphus commented, there should be some exception in the server standard output.
So you probably need to:
Return a different response code (e.g. INTERNAL_SERVER_ERROR or
BAD_REQUEST) in the catch block
Check why the server code is throwing
the exception
Most likely you get an Exception. I guess it is because you have "plant" in one place and "plan" in another.
okey so finaly it works what i need to change was the way that the service was reciving the data, with a inner class in my case, end up working like this ..
Class Aux{
String xml;
String plant;
//generate gettes and setters :)
}
#Path("/example")
public class PdfMaker {
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response PruebasMet(Aux json) throws IOException,
JSONException{
try{
String xml = json.getXml();
String plant = json.getPlant();
//method that uses "xml" and "plant" and returns "pdf"
JSONObject response = new JSONObject();
response.put("pdf", pdf);
return Response.status(200).entity(pdf)).build();
}catch(Exception e){
e.getStackTrace();
return null;
}
}
and the client is ..
Client client = new Client();
WebResource wresource = client.resource("http://localhost:8080/PdfMakerGF/rest/example/post");
JSONObject json = new JSONObject();
json.put("xml", DATA);
json.put("plant", DATA);
ClientResponse response =
wresource.type("application/json").post(ClientResponse.class,
json.toString());
out = response.getEntity(String.class);
System.out.println("RES = "+response);
System.out.println("OUT = "+out);
out has the info that the service is Providing

Java Jersey Web Service: consume JSON request

I have a web service made witj Java and Jersey. I want to receive a JSON request and parse the json for savethe values stores on the json on the database.
This is mi web service code:
#Path("companies")
public class Companies {
#Path("add")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public JSONObject addCompanies(JSONObject inputJsonObj){
String input = (String) inputJsonObj.get("company");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj;
}
}
The client side is made with AngularJS:
$scope.company = "";
$scope.submit = function(){
// Writing it to the server
//
var dataObj = {
company : $scope.company
};
var res = $http.post('http://localhost:8080/WS-Test2/crunchify/companies/add', dataObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
notify("succes");
});
res.error(function(data, status, headers, config) {
//alert( "failure message: " + JSON.stringify({data: data}));
notify("fail");
});
};
This is the error I'm getting when I pass the JSON to the web service:
Status Code:415
And this is the request I am sending:
{"company":"Testing2"}
This is my Network tab:
Without further configuration, JSONObject is not something that Jersey supports. You will just need to work with Strings
public String addCompanies(String json){
JSONObject inputJsonObj = new JSONObject(json)
String input = (String) inputJsonObj.get("company");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj.toString();
}
If you really want to use JSONObject you can check out this post.
See Also:
JAX-RS Entity Providers to learn how Jersey handle serialization an deserialization.

Change URL pattern of rest API

#Path("/ftocservice")
public class RestService {
#Path("{f}")
#GET
#Produces("application/json")
public Response convertFtoCfromInput(#PathParam("f") float f)
throws Exception {
DbCon db = new DbCon();
ArrayList<Student> students = db.getStudentList();
JSONArray jsonArray = new JSONArray(students);
String result = jsonArray.toString();
return Response.status(200).entity(result).build();
}
}
I'm using above source code to generate rest API and user is requesting through the API as follows.
http://localhost:8080/RestExample/RestService/ftocservice/23
I need to change the request URL as follows.
http://localhost:8080/RestExample/RestService/ftocservice?f=23
Please help to change the source code to change request URL as given. Thanks
Change to use #QueryParam instead:
#Path("/ftocservice")
public class RestService {
#GET
#Produces("application/json")
public Response convertFtoCfromInput(#QueryParam("f") float f)
throws Exception {
DbCon db = new DbCon();
ArrayList<Student> students = db.getStudentList();
JSONArray jsonArray = new JSONArray(students);
String result = jsonArray.toString();
return Response.status(200).entity(result).build();
}
}
See this link for more info on parameter types in JAX-RS.
This tutorial by Mkyong.com is also quite nice.
use #QueryParam instead of #PathParam

How to pass array of variables to REST URL in android?

I have to make registration using REST URL. REST services are written in Java now i have to pass the set of parameters in that secGameIds parameter is like this [100,102]. Example registration using Insomnia:::
{
"firstName":"parent111",
"lastName":"sadfsdf",
"email":"abc#bbc.com",
"date":"2000-06-09",
"phoneNum":"8765654454",
"gender":"male",
**"secGameIds":[0,0],**
"roleId":102
}
How should i provide secGameIds parameter value is it a ArrayList or Array?
for remaining values i have created JSONObject class object and adding values to that object and 'm appending that object to url
{
JSONObject json = new JSONObject();
json.put("fistName","aaa");
..
..
HttpPost post = new HttpPost(uri);
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
DefaultHttpClient client = new DefaultHttpClient();
httpresponse = client.execute(post);
}
where as for secGameId i have tried like below,
{
int[] secGameId = {100,102};
}
-- gives me an error in back-end like "nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of int[] out of VALUE_NUMBER_INT token"
I even tried by using
{
ArrayList<Integer> secGameId = new ArrayList<String>();
secGameId.add(100);
secGameId.add(102);
}
and passing to value...
{
json.put("secGameIds":secGameId)
}
again at server side i kicked with the same error.
Can anyone help me?
public static String httpPost(HashMap<String, String> map, String url,String token) {
Log.e("call ", "running");
HttpRequest request;
if(token!=null){
request = HttpRequest.post(url).accept("application/json")
.header("Authorization", "Token " + AppInfo.token).form(map);
}
else
request = HttpRequest.post(url).accept("application/json").form(map);
int responseCode = request.code();
String text = request.body();
Log.e("response", " "+responseCode+ " "+ text);
if(responseCode==400){
return "invalid_tocken";
}
else if(responseCode<200 || responseCode>=300) {
return "error";
}
return text;
}
Hope you can convert the JSONArray to HashMap. If you instead need to post it as a JSONArray itself, then OkHttp library will help you.

Categories

Resources