I am new to Spring Boot and I am trying to load a Json template file and replacing the placeholders with input values read from a user input file.
This is my JSON.
template.json
{
"templateId": "header",
"configurationData": {
"inboundHeaders": [
{
"key": "header1",
"value": {0}
}, {
"key": "header2",
"value": {1}
}, {
"key": "header3",
"value": {3}
}
],
"outboundHeaders": [
{
"key": "header4",
"value": {4}
}, {
"key": "header5",
"value": {5}
}, {
"key": "header6",
"value": {6}
}
]
}
}
So, here I want to replace these placeholders before sending it to remote service
public void processJson(List<String> userParams, String jsonFile){
HttpClient client = new ProductHttpClient();
mapper = new ObjectMapper();
JavaToJsonConverter converter = new JavaToJsonConverter();
RemoteServiceResponse response = null;
RequestPojo requestPojo = createRequestPojo();
List<Header> headers = new ArrayList<Header>();
headers.add(new BasicHeader("Content-Type", "application/json"));
headers.add(new BasicHeader("Authorization", "Bearer " + token.getAccessToken()));
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
String jsonRequest = MessageFormat.format(jsonFile, value1, value2, value3, value4, value5, value6); // This is the problem area which I am unable to achieve
//Working code
HttpResponse httpResponse = client.postRequest(url,
converter.convertToJson(requestPojo), urlParameters, headers);
//Not Working
HttpResponse httpResponse = client.postRequest(url,
jsonRequest, urlParameters, headers);
}
Presently, I am creating POJOs from request Json and replacing the placeholders while passing the request json to remote service. Here I see following issue
I was not able to load Json file from properties file. So, I had to generate POJOs every time for different request Json, fill object with user input value and convert those POJOs back to json string and submit to remote service.
But I just want to load the json file with placeholder and replace the placeholder with the user input values. It will save the overhead of creating so many POJOs many times.
So, can any one help on this?
Thanks in advance.
Related
I am trying to get value of TxnType from json request while mocking a response from SOAPUI. I want to respond with different responses based the value of TxnType.
{
"Request": {
"UserId": "user",
"TxnType": "fetch"
}
}
Here is the groovy script to fetch the request value with fixed json
def json = """{
"Request": {
"UserId": "user",
"TxnType": "fetch"
}
}"""
def transactionType = new groovy.json.JsonSlurper().parseText(json).Request.TxnType
log.info "TxnType is : ${transactionType}"
You may quickly try the Demo
If you want to use the dynamic json in the mock script, then you can use below mock script dispatcher
def transactionType = new groovy.json.JsonSlurper().parseText(mockRequest.requestContent).Request.TxnType
log.info "TxnType is : ${transactionType}"
// Pick Request Body
def requestBody = mockRequest.getRequestContent()
log.info "Request body: " + requestBody
// Pick TxnType value
def txnType = requestBody["TxnType"]
(or something like this)
I am returning the object directly in the GET request as following.
Ok(object);
and the response json is given as,
json data-->
{
"id":"1",
"name":"testname"
}
I want to add some more details to this json
-->
{
success:"true",
messageDetails:"The response is returned by the service",
data:{}
}
how to accomplish this?
can i club all the things in Ok(object) ??
You can make use of an anonymous type, for example:
object data = new { id = 1, name = "testname" };
return Ok(new
{
success = "true",
messageDetails = "The response is returned by the service",
data
});
I'm trying to make request to facebook REST APIs and in return getting a JSON Response. I'm able to collect the response in REST client, hence I know the requestUrl I'm using while creating HttpRequest in following code is correct. But when I try to mimick the GET using akka-http javadsl, I'm unable to understand how to extract the json from the ResponseEntity.
final HttpRequest request = HttpRequest.GET(requestUrl);
final Materializer materializer = ActorMaterializer.create(this.context.getActorSystem());
final CompletionStage<HttpResponse> responseFuture =
Http.get(this.context.getActorSystem()).singleRequest(request, materializer);
final HttpResponse response = responseFuture.toCompletableFuture().get();
I'm expecting a response something as follows -
{
"data": [
{
"cpc": 9.7938056680162,
"clicks": "247",
"impressions": "15949",
"spend": 2419.07,
"date_start": "2016-06-15",
"date_stop": "2016-08-13"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MAZDZD"
}
}
}
You should get response entity from response by calling ResponseEntity entity = response.entity() and after that call entity.toStrict(timeoutMillis, materialiser).data.decodeString("UTF-8") to get body string
You can lookup signatures of those methods in official API documentation
I am reading a big JSON file stored on the server, using WEB API. Following is the code snippet:
public HttpResponseMessage Get()
{
string filePath = "file path";
var response = Request.CreateResponse(HttpStatusCode.OK);
if (File.Exists(filePath))
{
response.Content = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
}
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return response;
}
Everything is working as expected. Apart from a string "Caffè", which is converted to "Caff". (è to space).
Does anyone know what's going on under the hood and the fix?
Sample of JSON file:
{
"id": 1,
"PartnerName":"Caffè Nero"
},
{
"id": 2,
"PartnerName":"XYZ"
},
JSON response of Get() method is returning right JSON except, Caffè Nero
Response:
{
"id": 1,
"PartnerName":"Caff Nero"
},
{
"id": 2,
"PartnerName":"XYZ"
},
I am trying to insert data into the MongoDb collection using postman. How would I approach this; hardcoding the data in JSON format works, but I want to be able to insert using postman in JSON format.
This is the code that allowed me to enter directly, using the post function in postman, with no input:
public async void Insert([FromBody]string value)
{
var client = new MongoClient();
var dbs = client.GetDatabase("test");
var collection = dbs.GetCollection<BsonDocument> ("restaurants");
BsonArray dataFields = new BsonArray { new BsonDocument {
{ "ID" , ObjectId.GenerateNewId()}, { "_id", ""}, } };
var document = new BsonDocument
{
{"borough",value },
{"cuisine","Korean"},
{"name","Bellaa"},
{"restaurant_id","143155"}
};
await collection.InsertOneAsync(document);
}
You can send it as raw data. You will set the post type to application/json.
This comes From the docs.