Passing date in json file in KarateFramwork - json

I have following function to get current date:
function() {
var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
var sdf = new SimpleDateFormat('yyyyMMdd');
var date = new java.util.Date();
return sdf.format(date);
}
And I'm passing the date to JSON file as follows:
* def currDate = getDate()
JSON File:
{
"clientId": "ABC",
"serviceLine": "DSS",
"locationId": "VOL",
"serviceType": "ADC",
"attendanceDate": #(currDate),
"saId": "123",
"attendance": "PRESENT",
"attendanceType": "ATTENDANCE"
}
Json by default converts date into string for e.g. "20230210" (yyyyMMdd). This format is fine & as expected. But just I pass the variable currDate to JSON, it converts it into String with "", e.g., "20230210" but request should have date without quotes, i.e. just 20230210. Otherwise it gives error as Invalid Input.
How can I convert string to date format in JSON file?

After seeing your comments, looks like you are just trying to use the date format output as a number. That's easy, just do this:
* def currDate = 1 * getDate()
Also refer: https://github.com/karatelabs/karate#floats-and-integers

Related

How to parse json data elements into domain object using groovy

We are using Grails version 3.2. I have the json response and Domain object like below. How can we parse json response into domain object using groovy to save in our db without manually converting all the json response elements into my domain properties.
json response
{
"orderId": 1,
"orderDateTime": "07/10/2020",
"orderTypeId": 1,
"userId": "12345",
"StateId": "5"
}
Domain object:
class Order {
Long id
Date orderDate
Long orderType
Long user
Long state
}
Use JsonSlurper
The JsonSlurper class can do this for you.
Simple example
The easiest way is like this:
json = new JsonSlurper().parseText( jsonStrIn )
order = new Order( json )
But that only works if:
Domain class property names match the JSON property names
Every domain property is either a String or has a setter that takes a String argument.
If that's not the case, as it isn't in the sample you provided, then it's a little more complex.
Mapping JSON properties to domain properties
To work around the name differences you can create a map of JSON names to domain names and use the map to modify the JSON string before you parse it.
Map propertyNameMap = [
'orderId': 'id',
'orderDateTime': 'orderDate',
'orderTypeId': 'orderType',
'userId': 'user',
'StateId': 'state'
]
propertyNameMap.each { jsonName, domainName ->
jsonStrIn = jsonStrIn.replaceAll( jsonName, domainName )
}
You might need to use a regular expression, if the JSON property names can occur in the value strings.
Worked example
The following code will populate your domain from the JSON, correctly translating from String to long (where needed) and allowing for differences in property names.
import groovy.json.JsonSlurper
import java.text.SimpleDateFormat
String jsonStrIn = '''{
"orderId": 1,
"orderDateTime": "07/10/2020",
"orderTypeId": 1,
"userId": "12345",
"StateId": "5"
}'''
#groovy.transform.ToString
class Order {
Long id
Date orderDate
Long orderType
Long user
Long state
void setOrderDate( String dt ) {
orderDate = new SimpleDateFormat('dd/MM/yyyy').parse( dt )
}
void setUser( String uid ) {
user = Long.parseLong( uid )
}
}
Map propertyNameMap = [
'orderId': 'id',
'orderDateTime': 'orderDate',
'orderTypeId': 'orderType',
'userId': 'user',
'StateId': 'state'
]
propertyNameMap.each { jsonName, domainName ->
jsonStrIn = jsonStrIn.replaceAll( jsonName, domainName )
}
println jsonStrIn
json = new JsonSlurper().parseText( jsonStrIn )
order = new Order( json )
println order
Code output
Running the above example will display the translated JSON and the Order instance created from it.
{
"id": 1,
"orderDate": "07/10/2020",
"orderType": 1,
"user": "12345",
"state": "5"
}
Order(1, Wed Oct 07 00:00:00 BST 2020, 1, 12345, 53)
[Done] exited with code=0 in 1.677 seconds```

How to handle data type wise XML to JSON conversion by using NewtonSoft

I am using NewtonSoft namespace to convert the xml data to json. I want the json data value to preserve the data type. But, by using "SerializeXmlNode" it is giving json data value in string.
XML Data is:
<statecode>1</statecode>
<iskit>false</iskit>
<name>PokeMon go</name>
<ExpirationDate>2013-12-31T00:00:00</ExpirationDate>
<price>25.00</price>
I am using the following code:
string requestData = #"<products><statecode>1</statecode>
<iskit>false</iskit>
<name>PokeMon go</name>
<ExpirationDate>2013-12-31T00:00:00</ExpirationDate>
<price>25.00</price></products>";
XmlDocument transformData = new XmlDocument();
transformData.LoadXml(requestData);
foreach(XmlNode data in transformData.GetElementsByTagName("products"))
{
string transformedJsonData = JsonConvert.SerializeXmlNode(data);
}
Output:
{
"statecode" : "1",
"iskit" : "false",
"name":"PokeMon go",
"ExpirationDate":"2013-12-31T00:00:00",
"price":"25.00"
}
Expected Output:
{
"statecode" : 1,
"iskit" : false,
"name":"PokeMon go",
"ExpirationDate":"2013-12-31T00:00:00",
"price": 25.00
}
You can observe output is in string.

Date Format in Json request/response of an API

I am having a Date field - startDate in my pojo.
In API request body in JSON I have to mention date in following format -
{
...
"startDate" : "2017-05-19T14:00:00",
...
}
But in the response I get the following format -
{
...
"startDate" : "2017-05-19 14:00:00",
...
}
There is no 'T' in the response JSON.
What should I do to make it consistent and have the 'T' in response as well.
You can use below code for yyyy-MM-dd'T'HH:mm:ss to yyyy-MM-dd HH:mm:ss at the time of request.
String time = "2017-05-19T14:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(time);
String formattedTime = output.format(d);
System.out.println(formattedTime);
OR
you can use below code for yyyy-MM-dd HH:mm:ss to yyyy-MM-dd'T'HH:mm:ss at the time of response.
String time = "2017-05-19 14:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date d = sdf.parse(time);
String formattedTime = output.format(d);
System.out.println(formattedTime);
There two ways to achieve the result.
Use String in server side.So you can get the same result in both
request and response.
You could convert date object into Long(millisecond).
For your information, The T is just a literal to separate the date from the time.
You can use the below code
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")

Using JPATH, how do I select a JSON value inside another JSON string?

I have the following JSON (simplified / minimized to show only pertinent parts) returned from a web service:
{
"results": [{
"paramName": "OutputPolyline",
"dataType": "String",
"value": "#{\"hasM\":true,\"paths\":[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]}"
}],
"messages": []
}
I use the following code to parse the JSON and grab the value of the "value" key:
JObject obj = JObject.Parse(json);
JToken token = obj.SelectToken("$.results[?(#.paramName == 'OutputPolyline')]['value']");
Console.WriteLine(token.Path + " -> " + token);
The above code returns the entire value string as expected, like such "#{\"hasM\":true,\"paths\":[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]}"
Building on the above code, how do I get only the value of the paths key? In this example, return only [[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]
You cannot extract the path values from the root object via a single JsonPath query since the value of the value property is just a string literal that happens itself to be re-serialized JSON. It needs to be extracted and recursively parsed as JSON after first trimming off the # character, and Json.NET has no built-in query operator to do that as of the current version, 9.0.1.
Thus you need to do something like:
JToken token = obj.SelectToken("$.results[?(#.paramName == 'OutputPolyline')]['value']");
var paths = JToken.Parse(token.ToString().Trim('#')).SelectToken("paths");
Sample fiddle.

Json String Date to date Object with AngularJS Http get

I am trying to order a list by date and popularity. From service i have a json response which has date in string format. Is it possible to change the date from Http get response to date object so that i want to use OrderBy filter to sort the list by date.
My json is
{
"Name": "Paul ",
"Country": "SINGAPORE",
"Date": "12/31/14 20:40",
"Rating": "2"
}
You could pass the date string to the Date Object
Put this in your controller:
myApp.controller("MyPersonController", function($scope){
for (var i in $scope.persons) {
$scope.persons[i].Date = new Date($scope.persons[i].Date);
}
});
If you have problems with formatting, I would recommend a date wrapper like MomentJs