How to match an json value representing timestamp with floating point? - java

My REST service returns json like this:
{"lastWriteTime":1525507872.123000000 .... }
how do I match it in my mockMvc test using jsonPath statement?
when I try to use an is or equalTo matcher, like this:
andExpect(jsonPath("$.elements[0].lastWriteTime", equalTo(1525507872.123000000)))
I keep getting this kind of error in different flavours:
java.lang.AssertionError: JSON path "$.elements[0].lastWriteTime"
Expected: <1.525507872123E9>
but: was <1525507872.123000000>
casting the value to double or specifying as string doesn't seem to work.

Related

Hamcrest matchers to check JSON filed value is null or empty?

I am using hamcrest for first time, i have developed a framework to validate particular JSON field values need to satisfy some business rules, i am trying to check on of the field in JSON should not be " " or null. Please find below for the code,matcherOperator validate JSON field against a Array of values for example in ISINARRAY validate the JSON filed is present in the following list of array values [1,2,3,4] similarly NOTINARRAY validate the JSON filed should not be present given range of array values. I am trying to check whether given field is empty or null i defined array like this [null,""] and using NOTINARRAY to check JSON key value shouldn't be null or "" for null its working but the JSON value is "" its validating to true and i tried using Matchers.blankOrNullString() too but its not working and i saw two question of similar type but they are part of JUNIT testing which i tried to used but not working below are the question i referred
Hamcrest matcher with slashes is interpreted as a part of validation
Hamcrest check if value is null or empty array
public <T extends Comparable<T>> Matcher<String> mymatcher(final FieldOperator matcherOperator,
final List<String> value)
{
switch (matcherOperator) {
case ISINARRAY: {
return Matchers.in(value);
}
case NOTINARRAY: {
return Matchers.not(Matchers.in(value));
}
}
I am not sure where i am doing wrong please help me in solving the issue.

Android - Converting string to list to push to firebase realtime database

Is there any way to convert the string below to a list?
This string is retrieved after scanning a QR code.
CashRequest{
orderid='0',
user_id='nvHt2U5RnqUwXB4ZK37Zn1DXPV82',
userName='username',
userEmail='whateveremailthisis#email.blabla',
fullName='full name',
phoneNumber=0,
totalCash='$304.00',
totalRV='$34.00',
foods=[
Order{
userID='nvHt2U5RnqUwXB4ZK37Zn1DXPV82',
ProductID='-LMDiT7klgoXU8bQEM-4',
ProductName='Coke',
Quantity='4',
Price='1',
RedemptionPrice='10',
RedemptionValue='1'},
Order{
userID='nvHt2U5RnqUwXB4ZK37Zn1DXPV82',
ProductID='1000',
ProductName='Kunau Ring Ring Pradu',
Quantity='3',
Price='100',
RedemptionPrice='10',
RedemptionValue='10'
}
]
}
The desired output is to store it in firebase realtime database as below :
Well you have a few options. Since it is newline between values, you could use simple newline reads and compare if it starts with "reserved word that you are looking for" then substring from there, but that can get messy and a lot of bloat code.
The simplest way would be to do the known replace first.
Make a method that replaces all bad json keys with quote surrounded json keys like:
val myJsonCorrected = yourStringAbove.replace("Order", "\"Order"\")
repeat for all known entities until you have made it into valid json. Single ticks are fine for the values, but the keys need quotes as well.
Then simply create an object that matches the json format.
class CashRequestModel{
#SerializableName("orderid")
var orderID: Int? = null
etc.....
#SerializableName("foods")
var myFoods: ArrayList<OrderModel>? = null
}
class OrderMode {
#SerializableName("userID")
var userID: String? = null
#SerializableName("ProductID")
var userID: String? = null
etc..
}
Then simply convert it to JSON
val cashRequest = getGson().fromJson(cleanedUpJson, classTypeForCashRequest);
and your done. Now just use the list. Of course it would be better if you could get valid JSON without having to clean it up first, but it looks like the keys are known and you can easily code string replaces to fix the bad json before casting it to object that matches the structure.
Hope that helps.

Java: JSONParseException

All I'm trying to do is to parse very simple json line, even its valid i dont know why its throwing an error
the line is
com.mongodb.util.JSONParseException:
{publish_status:'active',activation_date:{$lt:new Date()},expiration_date:{$gt:new Date()}}
^
what is wrong with the new Date() as a value?
That's not valid JSON at all. JSON syntax is defined on json.org, and it's always a string key with a value that's one of a string, number, boolean, null, array, or object. You're writing a Mongo query from Java. You should reformulate your question and retag appropriately.
I tried using the new date() in mongo DB 2.2.3 directly and it worked .. it created a value of ISODate.
You may try using this:
{publish_status:'active',activation_date:new Date(),expiration_date:new Date()}

Reading Json String using Gson results error "not a JSON Array"

In my project i have a complex json response. I want to read it by GSon.
JSON : {'FoodMenuRS':{'Results':[{'Items':{'Item':[{'#Id':'24'},{'#Id':'24'}]}}, {'Items':{'Item':{'#Id':'24'}}}]}}
It contains a JSONArray with first "Item" and JSONObject with second one. Hence its call results in error,
failed to deserialize json object {"#Id":"24"} given the type java.util.List<com.servlet.action.ItemInfo> and java.lang.IllegalStateException: This is not a JSON Array.
Please help how i should handle this scenario. Thanks.
The string you are showing is a JSONObject not a JSONArray. So, in this case you first of all have to get the JSONObject and perform further decoding on that JSONObject.
JSONObject - {}
JSONArray - []
And indeed JSONObject or JSONArray should be encoded using Double-quotes(")
Your JSON is valid, but not for the doble quotes (") because JSON supports simple quotes (') and no quotes in the key name. See http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Colle
However this JSON have key names that begin with #. For JSON strings this character is valid at the beginning of the name (see right column http://www.json.org/) but for Java this names are illegal (see Naming section http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html). Specifically, names started with # are annotations and you can't use annotations tags to declare variables, fields, methods, etc.
This is not a valid JSON object. Strings in JSON are always encapsulated in double quotes ("). Contact the producer of that JSON and tell him to use a correct encoder.

java types in org.bson.BSONObject

I'm currently learning the BSON java library for mongodb and I'm trying to transform a org.bson.BSONObject into XML in order to transform it with a XSLT stylesheet.
What kind of java types can I find as values in a BSONObject from a Mongodb ? Of course there will be:
BSONObject (internal doc)
java.lang.String
???
what are the others ? BigDecimal and BigInteger ? boolean, int, long, double ? Timestamp.. etc... ??
thanks,
Pierre
Had to search for it too, but according to this mongodb-dev post mapping is done like this:
NULL null
UNDEFINED null
BOOLEAN Boolean
NUMBER Double
NUMBER_INT Integer
NUMBER_LONG Long
SYMBOL String
STRING String
OID mongodb ObjectID
REF DBPointer
DATE Date
REGEX Pattern
BINARY DBBinary
CODE (exception)
ARRAY DBList
OBJECT DBObject or DBRef
TIMESTAMP DBTimestamp
MINKEY String: "MinKey"
MAXKEY String: "MaxKey"
This article on mongodb.org is a good resource for it, too.
Edit: Had a look at the source: org.bson.types.* is having a number of classes for BSON types. org.bson.BSONDecoder is decoding a BSON string and does the mapping listed above.
One alternative way to operate on BSON would be to use Jackson JSON processor; although by default it operates on JSON, there are extensions to use it both on BSON and XML. Since Jackson does data binding, you can bind BSON data into Java POJOs (with bson4jackson) and write out as XML (with jackson-xml-databind).
Transformation would be as simple as:
String xml = xmlMapper.writeValue(bsonMapper.readValue(bsonData, MyPojo.class));
if you have, or can create, MyPojo that maps all properties; or if not by specifying Map.class as the intermediate type to bind to.

Categories

Resources