I working with java 8 and the following spring specification:
<spring.version>4.2.3.RELEASE</spring.version>
<spring.security.version>4.0.3.RELEASE</spring.security.version>
<spring.data.version>1.8.1.RELEASE</spring.data.version>
I have a document that obviously has an _id, which is working perfectly, but I have another field that stores a reference that is another _id, this is my expected JSON
{
"_id" : ObjectId("56c8f330d4c65e543ceac8de"),
"companyId" : ObjectId("56c8f330d4c65e543ce8c8de"),
"name" : "COMPANY S.R.L",
more fields......
}
I have created the following converter:
#Component
public class PurchaseWriterConverter implements Converter<Purchase, DBObject>
{
#Override public DBObject convert(Purchase source)
{
DBObject dbo = new BasicDBObject();
dbo.put("_id", source.getId());
**ObjectId objCompany = new ObjectId(source.getCompany().toString(16));
dbo.put("company", objCompany);**
dbo.put("supplier", source.getSupplier());
dbo.put("status", source.getStatus().toString());
dbo.put("attendant", source.getAttendant());
dbo.put("cashier", source.getCashier());
List<Object> orders = new BasicDBList();
for (OrderWrapper order : source.getOrders())
{
DBObject orderDBObject = new BasicDBObject();
orderDBObject.put("description", order.getDescription());
orderDBObject.put("basePrice", order.getBasePrice());
orderDBObject.put("grossWeight", order.getGrossWeight());
orderDBObject.put("netWeight", order.getNetWeight());
orderDBObject.put("subtotal", order.getSubtotal());
orderDBObject.put("totalWeight", order.getTotalWeight());
orders.add(orderDBObject);
}
dbo.put("orders", orders);
dbo.put("createDate", source.getCreateDate());
dbo.put("updateDate", source.getUpdateDate());
dbo.put("approvedBy", source.getApprovedBy());
dbo.put("createDate", source.getCreateDate());
dbo.put("updateDate", source.getUpdateDate());
dbo.removeField("_class");
return dbo;
}
}
The following lines are not working
dbo.put("_id", source.getId());
**ObjectId objCompany = new ObjectId(source.getCompany().toString(16));
So, I tried to create another converter in order to convert BigInteger to ObjectId, something like this
public class BigIntegerToObjectIdConverter implements Converter {
#Override
public ObjectId convert(BigInteger source) {
return source == null ? null : new ObjectId(source.toString());
}
}
But I getting the same error:
org.springframework.core.convert.ConversionFailedException: Failed to convert from type com.xxxxxxxxxxx.entity.Purchase to type com.mongodb.DBObject for value 'Purchase{company=1, orders=[com.xxxxxxx.equilibrium.wrapper.OrderWrapper#9cd3f65], supplier=26857458392532697059830357595, approvedBy='', status=TO_BE_APPROVED, attendant='User Admin', cashier=''}'; nested exception is java.lang.IllegalArgumentException: invalid ObjectId [1]
the value that I sending as a biginteger is "1".
Can anybody gives me some directions about how to convert a BigInteger to ObjectId or suggest something different.
I just answered to a similar question here https://stackoverflow.com/a/46508892/4660481
A valid ObjectId can be constructed from exactly 24 hexadecimal characters. In this case, your .toString(16) will return "1" which does not have a length of 24. What you would want in this case is "000000000000000000000001". You can resolve this issue by padding with 0s:
String hexString24 = StringUtils.leftPad(source.getCompany().toString(16), 24, "0");
ObjectId objCompany = new ObjectId(hexString24);
Related
I am having a string like ,
name = " {
"Name" : "MyName"
}"
and having a Model class like ,
#Valid
Class Model {
#JsonProperty("Name")
#Size(min = 1)
#NotNull
private String name;
}
Now I am converting the string to Java Object by following code,
Model name = objectMapper.readValue(name, Model.class);
So the validation(min = 1 and not null) is not happening with this.
How can I validate when I am converting a string to java object?
i will try to help u.
I have an idea and it´s that u divide the process in 2 parts:
First, u take the json and put in on a JSONObject:
import org.json.JSONObject;
...
JSONObject json= new JSONObject(name);
Then, u can call, for example, a function passing a json that validate the values of json an if is correct return a model object:
public Model functionExample(JSONObject json){
try{
if(json.has("Name") && json.getString("Name")!=null){
return new Model(json.getString("Name"));
}
}catch(Exception ex){
return new Model();
}
}
This check if the field "Name" exists and it´s not null.
I don´t know if it is what u want.
I hope it help u.
I'm trying to deserialize an array of json object to array of java Object. I'm using data provider to pass this data combination to test methods so test method executes for each data set.
I've created Data provider method as mentioned below and deserilised the Json:
#DataProvider(name = "listData")
public Object[][] listData() throws FileNotFoundException {
Type listType = new TypeToken<List<DataBean>>() {
}.getType();
List<DataBean> data = new GsonBuilder().create().fromJson(new FileReader("resources/data.json"), listType);
data.forEach(iterator -> System.out.println(iterator.getUsername() + " : : " + iterator.getPassword()));
return new Object[][]{data.toArray()};
}
Test method :
#Test(dataProvider = "jsonData")
public void testdata(DataBean dataBean) {
System.out.println(dataBean.getUsername() + "============" + dataBean.getPassword());
}
and JSON :
[
{
"username": "someuser",
"password": "abc#add"
},
{
"username": "anotheruser",
"password": "daa#add"
}
]
Unfortunately its not working. If i use Strong typed Object like below then its work as expected :
return new Object[][]{{new DataBean("user1", "d121312")},
{new DataBean("user2", "asdsd")}};
Error:
org.testng.internal.reflect.MethodMatcherException: [public void
com.mind.DataProviderUtil.testdata(com.mind.DataBean)] has no
parameters defined but was found to be using a data provider (either
explicitly specified or inherited from class level annotation). Data
provider mismatch Method: testdata([Parameter{index=0,
type=com.mind.DataBean, declaredAnnotations=[]}]) Arguments:
[(com.mind.DataBean) com.mind.DataBean#78b66d36,(com.mind.DataBean)
com.mind.DataBean#5223e5ee]
Can someone please help me int storing List<DataBean> data in Object[][] so my test method execute for each set of data
Data stores in 2-D array in matrix form.
Lets say there is an array of 3x3 then matrix representation would be
1 2 1
3 4 2
1 2 1
As data provider return 2-D array to supply data to Test method for Data Driven test. So need to mention Object[][] with proper size. I've 2 sets of data in JSON file and I'm deserializing to a JAVA object that is DataBean in my case. So here I have to mention sizes as Object[dataBean.size()][1]
Complete Code:
Type listType = new TypeToken<List<DataBean>>() {
}.getType();
List<DataBean> bean = new GsonBuilder().create().fromJson(new FileReader("resources/data.json"), listType);
bean.forEach(iterator -> System.out.println(iterator.getUsername() + " : : " + iterator.getPassword()));
Object[][] data = new Object[bean.size()][1];
for (int i = 0; i < bean.size(); i++) {
data[i][0] = bean.get(i);
}
return data;
I'm performing a Mongo query. My results contain decimalnumber data.
How can I set my cost data in a java DecimalNumber attribute?
{
"macroType" : "LIBRI",
"costType" : {
"$numberDecimal" : "4.60"
},
"count" : 3
}
It's a document that I add in a List.
In the code below ai is my list.
I want to set costType in the BigDecimal attribute
Now I don't know how can do it.
Thanks in advance.
for (int i = 0; i < ai.size(); i++) {
String json = new GsonBuilder().create().toJson(ai.get(i));
JsonElement je = new com.google.gson.JsonParser().parse(json);
JsonObject root = je.getAsJsonObject();
JsonElement je2 = root.get("costType");
}
After fetching data from database in the document,
You can convert numberDecimal field into the BigDecimal by...
BigDecimal cost = new BigDecimal(document.get("costType",Document.class).getString("$numberDecimal"));
System.out.print(cost);
System.out.println(cost.getClass());
O/p:
4.60 class java.math.BigDecimal
Old question but this might help someone. You can just use org.bson.json.JsonWriterSetting like so:
JsonWriterSettings settings = JsonWriterSettings.builder()
.decimal128Converter(new Converter<Decimal128>() {
#Override
void convert(Decimal128 value, StrictJsonWriter writer) {
writer.writeNumber(value.toBigDecimal().toPlainString())
}
})
.build();
yourDocument.toJson(settings); // org.bson.Document
I need to create a JSON response with some dynamic fields in java. Here is an example of the JSON response I want to return :
{
"success": true,
"completed_at": 1400515821,
"<uuid>": {
type: "my_type",
...
},
"<uuid>": {
type: "my_type",
...
}
}
The "success" and the "completed_at" fields are easy to format. How can I format the fields? What would be the corresponding java object?
Basically I want to work with 2 java objects :
public class ApiResponseDTO {
private boolean success;
private DateTime completedAt;
...
}
and
public class AuthenticateResponseDTO extends ApiResponseDTO {
public List<ApplianceResponseDTO> uuids = new ArrayList<ApplianceResponseDTO>();
}
These java objects don't correspond to the expected JSON format. It would work if I could change the JSON format to have a list, but I can't change it.
Thanks a lot!
You can massage your data into JSON form using the javax.json library, specifically the JsonObjectBuilder and the JsonArrayBuilder. You'll probably want to nest a few levels of a toJson() method which will either give you the string representation you're looking for, or the JsonObject/JsonArray you desire. Something like this:
JsonArray value = null;
JsonArrayBuilder builder = Json.createArrayBuilder();
for (ApplianceResponseDTO apr : uuids) {
builder.add(apr.toJson());
}
value = builder.build();
return value;
I have a JSON in MongoDB with the following structure:
{
id:"_234234",
"stationId":"ALM",
"storageData": {
}
}
To retrieve JSON with storageData equal to null, in MongoDB I query as:
db.collection.find({"storageData":{"$gt" : {}}})
It gives me list of JSON bodies with empty storageData. So how do I represent that in Java
BasicDBObject obj=new BasicDDBObject("storageData", new BasicDBObject("$gt",{}));
collection.find(obj);
I am getting an error near BasicDBObject("$gt",{}))...
How do I represent ("$gt",{}) in Java??
First understand that null is a valid value. This would be valid:
{
id:"_234234",
StationId:"ALM",
StorageData: null
}
and retrieving the document, asking for storagedata which is null would retrieve the doc with the id _234234.
If what you need is to check which documents DON'T have the key "storagedata" then use the $exist keyword or construct the query in this way:
db.yourcollection.find("this.storagedata == null")
I would do it via query, and not in Java because it would alleviate cpu time and memory.
All you want to to here is represent an empty object:
BasicDBObject query = new BasicDBObject(
"storageData", new BasicDBObject(
"$gt",new BasicDBObject()
)
);
Which of course produces the query:
{ "storageData" : { "$gt" : { } } }
So that's it, just call BasicDBObject without any arguments.