Unexpected JSon response from Spring Rest API Controller - java

I have a method in my Spring controller, in which I am returning an object containing a spring attribute with a value "\HelloWorld". To store it into Java String object I have to put escape character, then the string becomes "\\HelloWorld". When I print, that works totally fine and prints "\HelloWorld". but when I return it in JSon response, it's returning "\\HelloWorld".
But I want it to return "\HelloWorld".
Bellow is the snippet:
#RequestMapping("")
#ResponseBody
public MyDataObject greeting() {
MyDataObject f = new MyDataObject();
f.setMessage("\\HelloWorld");
return f;
}
It's Json response is "message":"\\HelloWorld", but I want it "\HelloWorld".
Note: I don't want to unescape manually specific to that string.

You can use a library such as Jakson and it will internally handle such complexities.
MyDataObject f = new MyDataObject();
f.setMessage("\\HelloWorld");
String payload = new ObjectMapper().writeValueAsString(params);

Related

how process comma separated parameter passed by angular in spring boot API

I am using angular 6 as front end. Using front end input I want to know the status of tracking id 3,5,6. How to process this. Below is my code:
Angular service code:
getConsignmentByTrackingid(trackingid): Observable<any> {
console.log(trackingid);
//tracking ids are : 3,5,6
return this.http.get(`${this.baseUrl}/trackingid/${trackingid}`);
}
Spring boot controller code:
#GetMapping(value = "/tracking_history/trackingid/{trackingid}")
public ResponseEntity<List<Tracking>> findByTrackingId(#PathVariable String trackingid){
try{
List<Tracking> trackings = trackingRepository.findByTrackingId(trackingid);
if (trackings.isEmpty())
{
return new ResponseEntity<List<Tracking>>(HttpStatus.NO_CONTENT);
//return new ResponseEntity<>(trackings, HttpStatus.NO_CONTENT);
}
//System.out.println(trackings);
//output of system.out.println is : 3,5,6.
//How can I return these numbers one by one
return new ResponseEntity<>(trackings, HttpStatus.OK);
}
}
IMO if you need to send data in the form of array or object then you should not use query parmas or params in the HTTP.
In this case Request type should be POST/PUT and you should pass the data in the body part like below -
http.post(url, {body: setOfIds})

Rest Assured code not allowing to use println

I am trying to automate twitter API. when tried to print "js.get("text") using
System.out.println(js.get("text")); I am getting error as
"The method println(boolean) is ambiguous for the type PrintStream"
I downloaded jars and passed in Build path as well "scribejava-apis-2.5.3" and "scribejava-core-4.2.0"
Below code is not allowing me use println for ------>js.get("text")
public class Basicfunc {
String Consumerkeys= "**************";
String Consumersecretkeys="*******************";
String Token="*******************";
String Tokensecret="***************************";
#Test
public void getLatestTweet(){
RestAssured.baseURI = "https://api.twitter.com/1.1/statuses";
Response res = given().auth().oauth(Consumerkeys, Consumersecretkeys, Token, Tokensecret).
queryParam("count","1").
when().get("/home_timeline.json").then().extract().response();
String response = res.asString();
System.out.println(response);
JsonPath js = new JsonPath(response);
System.out.println(js.get("text"));
}
}
Use System.out.println(js.getString("text")); instead of System.out.println(js.get("text"));, because get returns any primitive value.
I think your problem is that your twitter response is actually a list.
Try to use System.out.println(js.getList()[0].get("text")); and be aware that you are only using the first [0] entry and ignoring the rest.

How to use OpenFeign to get a pojo array?

I’m trying to use a OpenFeign client to hit an API, get some JSON, and convert it to a POJO array.
Previously I was simply getting a string of JSON and using Gson to convert it to the array like so
FeignInterface {
String get(Request req);
}
String json = feignClient.get(request);
POJO[] pojoArray = new Gson().fromJson(json, POJO[].class);
This was working. I would like to eliminate the extra step and have feign auto decode the JSON and return a POJO directly though, so I am trying this
FeignInterface {
POJO[] get(Request req);
}
POJO[] pojoArray = feignClient.getJsonPojo(request);`
I am running into this error
feign.codec.DecodeException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 2 path $
Both methods used the same builder
feignClient = Feign.builder()
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.target(FeignInterface.class, apiUrl);
Anyone have any ideas?
You have broken JSON payload. Before serialising you need to remove all unsupported characters. Feign allows this:
If you need to pre-process the response before give it to the Decoder,
you can use the mapAndDecode builder method. An example use case is
dealing with an API that only serves jsonp, you will maybe need to
unwrap the jsonp before send it to the Json decoder of your choice:
public class Example {
public static void main(String[] args) {
JsonpApi jsonpApi = Feign.builder()
.mapAndDecode((response, type) -> jsopUnwrap(response, type), new GsonDecoder())
.target(FeignInterface.class, apiUrl);
}
}
So, you need to do the same in your configuration and:
trim response and remove all whitespaces at the beginning and end of payload.
remove all new_line characters like: \r\n, \r, \n
Use online tool to be sure your JSON payload is valid and ready to be deserialised .

how to return data in json format to javascript ajax call

I have the following method:
public String getUTResult() throws IOException {
BuildResultParser bp = new BuildResultParser();
BuildResultBean b = bp.getreadFile("C:\\bc.txt");
String str = b.getuTresult();
return str;
Now str variable contains the value as: [0,5,5]
Now I need to pass this value to ajax call in javascript in following format:
unittest
{
fail:0
pass:5
total:5
}
Actually in javascript, I need this data in array format so that I can access each value and do some processing.
Read this : http://hmkcode.com/java-servlet-send-receive-json-using-jquery-ajax/ or any example of converting data to json format.
If your requirement is limited to the example, u can have another function which takes str and creates json data out of it, in the format required by you.

Empty object in browser when returning JSONObject

I have this method :
#GET
#Path("/myservice")
#Produces(MediaType.APPLICATION_JSON)
public Response mysercice() {
boolean userExists = false;
CacheControl cacheControl = new CacheControl();
cacheControl.setNoCache(true);
cacheControl.setNoStore(true);
JSONObject jsonObject = new JSONObject();
jsonObject.put("userExists", userExists);
return Response.ok(jsonObject, MediaType.APPLICATION_JSON).cacheControl(cacheControl).build();
}
When accessing to the URL of the method in the browser, I get { }, it means that the object is empty.
So, I tried to use :
return Response.ok(jsonObject.toString(), MediaType.APPLICATION_JSON).cacheControl(cacheControl).build();
So, I get in the browser {"userExists" : false}
But I didn't understand why when returning simply the JSONObject, we get in the browser an empty object.
Most JAX-RS implementations come with a provider for mapping response entities to JSON. So when you write:
return Response.ok(jsonObject, MediaType.APPLICATION_JSON).build();
You are basically requesting that the JAX-RS provider marshall the JSONObject into JSON for you. The only problem being that JSONObject isn't really meant to be serialized this way. Instead its meant to be used to build a JSON representation incrementally, then convert that representation into a JSON string value. You have two options:
Create a POJO containing all the fields you want to send back to the client. Return this POJO in your method and it will be automatically converted to JSON (`return Response.ok(myPojo, MediaType.APPLICATION_JSON).build()
Return the JSON data directly as a String (which you already did in your example that works).

Categories