Convert mongo decimal number to java BigDecimal - java

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

Related

How create a (key, value) in JsonArray

I have a JSONObject, like the output in this link:
https://hadoop.apache.org/docs/r1.0.4/webhdfs.html#GETFILESTATUS
I woul dlike to get the pathSuffix (file names) and the modificationTime (Dates) values in a JSON Array, like this:
[
{ file1, date
},
{ file1, date
},
{ file1, date
},
.
.
.
]
My code is the following:
JsonObject fileStatuses = jsonObject.getJsonObject("FileStatuses");
JsonArray fileStatus = (JsonArray) fileStatuses.getJsonArray("FileStatus");
for (int i = 0; i < fileStatus.size(); i++) {
JsonObject rec = fileStatus.getJsonObject(i);
String pathSuffix = rec.getString("pathSuffix");
String modificationTime = rec.getJsonNumber("modificationTime").toString();
long a = Long.parseLong(modificationTime);
Date modificationTimeDate = new Date(a);
JsonObject jo = Json.createObjectBuilder()
.add("list", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add(pathSuffix, (JsonValue) modificationTimeDate)
))
.build();
logger.info("JSON object is '{}'", jo);
I got this Exception:
Exception in thread "main" java.lang.ClassCastException: java.util.Date incompatible with javax.json.JsonValue
How can I create a JsonArray that contain the values of Pathsuffix and ModificationTime like (key, value) ? Thanks
If you want to store a JSON-Object filename:modificationTime you can accomplish this by constructing a Map that holds your key and value pairs:
JsonArrayBuilder builder = Json.createArrayBuilder();
for (int i = 0; i < fileStatus.size(); i++) {
JsonObject rec = fileStatus.getJsonObject(i);
String timeStamp = rec.get("modificationTime").toString();
Map<String, Object> jsonMapping = Map.of(rec.getString("pathSuffix"),
timeStamp);
builder.add(Json.createObjectBuilder(jsonMapping));
}
After that, for the json from your Link, builder.build() will yield a JsonArray like this:
[
{
"a.patch":"1320171722771" // FileStatus.pathSuffix : FileStatus.modificationTime
},
{
"bar":"1320895981256"
}
]
Unless you need to construct a certain Date from the timestamp I stronlgy advice to store the acquired timestamp as is. This is because creating any LocalDate (or worse: Date) from a timestamp will yield inaccurate dates unless you consider the TimeZones of both where the file modification happened and where the modificationTime value is read.
json does not support a time type, that is the reason for the error. What you need to do is to change that into a type json can use. That might be a string that represents the time (choose the formating yourself, so you are sure, that when reading it out again you have consistent data) or easier you just keep the long value used.
Here you cansee what json can use:
https://www.json.org/json-en.html
try this json structure
[
{
fileName:"test.java",
modificationTime:"2021-03-02 xx:xx:xx"
},
{
fileName:"test2.java",
modificationTime:"2021-03-01 xx:xx:xx"
}
]

replace null to empty string in Java

I have below string output :
["Kolkata","data can be, null",null,"05/31/2020",null]
but I want to have the output like below format in Java
["Kolkata","data can be, null","","05/31/2020",""]
please help me .
I am converting object to json data . Please see the below codes
List<String> test = new ArrayList<>();
List<Object[]> data =query.list();
for (int i = 0; i < data.size(); i++) {
Object[] row = (Object[]) data.get(i);
String jsonString = gson.toJson(row);
test.add(jsonString);
}
I want to apply this on jsonString variable using java 7 as not using java 8
If you have list for example list of like this
List<String> list = Arrays.asList("Kolkata","data can be, null",null,"05/31/2020",null);
list.replaceAll(t -> Objects.isNull(t) ? "''" : t);
System.out.println(list);
Here oputput will be:
[Kolkata, data can be, null, '', 05/31/2020, '']

How to retrieve and update json array element without traversing entire json

I have a very complex json structure. It contains many array elements and those array elements contains other array elements and so on..
Please see below json tree structure.
Json Tree Structure-1 :
Json Tree Structure-2 :
As highlighted above in yellow, I want to update the value of "rdKey" field.
I wrote below code and it is perfectly working fine :
String json = "escaped string (as it's a big string, I can't put it here)";
JSONObject jsonObj = new JSONObject(json);
if (jsonObj.has("responseMap")) {
JSONObject responseMap = jsonObj.getJSONObject("responseMap");
if (responseMap.has("ValueJson")) {
JSONObject valueJson = responseMap.getJSONObject("ValueJson");
if (valueJson.has("ticketBean_CM")) {
JSONObject ticketBean_CM = valueJson.getJSONObject("ticketBean_CM");
if (ticketBean_CM.has("addByGamma")) {
String addByGamma = ticketBean_CM.getString("addByGamma");
System.out.println(addByGamma);
if (addByGamma.equals("VCE")) {
if (responseMap.has("ScreenJson")) {
JSONObject screenJson = responseMap.getJSONObject("ScreenJson");
if (screenJson.has("sections")) {
JSONArray sectionArray1 = screenJson.getJSONArray("sections");
if (sectionArray1.length() > 0) {
JSONObject section0 = sectionArray1.getJSONObject(0);
if (section0.has("sections")) {
JSONArray sectionArray2 = section0.getJSONArray("sections");
if (sectionArray2.length() > 3) {
JSONObject section6 = sectionArray2.getJSONObject(3);
if (section6.has("sections")) {
JSONArray sectionArray3 = section6.getJSONArray("sections");
if (sectionArray3.length() > 1) {
JSONObject section8 = sectionArray3.getJSONObject(1);
if (section8.has("elements")) {
JSONArray elementsArray1 = section8
.getJSONArray("elements");
if (elementsArray1.length() > 0) {
JSONObject elements1 = elementsArray1.getJSONObject(0);
if (elements1.has("elements")) {
JSONArray elementsArray2 = elements1
.getJSONArray("elements");
if (elementsArray2.length() > 4) {
JSONObject elements2 = elementsArray2
.getJSONObject(4);
if (elements2.has("rdKey")) {
System.out.println(
elements2.getString("rdKey"));
elements2.put("rdKey",
"CircuitID(FullPartial)");
System.out.println(
elements2.getString("rdKey"));
System.out.println(jsonObj.toString());
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
I want you guys to help me if there is any better solution for this. Can I do it without traversing the entire json object (till I find the concerned field) ? This solution will not work if json tree structure gets changes, it needs to be static as a success scenario of this code.
Please suggest better solution.
If you want to escape traversing of JSON then you can use JSONPointer, available in same org.json library.
E.g.:
String query = <json_pointer_query to element array>
JSONPointer pointer = new JSONPointer(query);
JSONObject elementsArrayJSON = (JSONObject) pointer.queryFrom(jsonObj);
elementsArrayJSON.put("rdKey","CircuitID(FullPartial)");
JSON Pointer query language can be referred in:
https://www.rfc-editor.org/rfc/rfc6901
Note:
JSON Pointer is pretty basic, it doesn't support wild card. So you need to be sure about element names, otherwise it would throw exception.
If you're flexible on what library to use, maybe the JsonPath will be useful for you.
You can update all "elements" with "rdKey" using the following code:
JsonPath.parse(json).set("$..elements[?(#.rdKey)].rdKey", "CircuitID(FullPartial)").json()

Parsing JSON Data (Android)

Alright. I have a JSON Object sent to me from a server which contains the following data:
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
}
The data I want to get is the status for the three status values. Data1, data2, and data3 always show up in that order, so I'm now trying to grab the data by index (e.g. data1 = index 0, data2 = index 1, data3 = index 2). How do I do that?
Try following:
String stat1;
String stat2;
String stat3;
JSONObject ret; //contains the original response
//Parse to get the value
try {
stat1 = ret.getJSONArray("results").getJSONObject(0).getString("status");
stat2 = ret.getJSONArray("results").getJSONObject(1).getString("status");
stat3 = ret.getJSONArray("results").getJSONObject(2).getString("status");
} catch (JSONException e1) {
e1.printStackTrace();
}
You would use JSONObject and JSONArray, the entire string is one JSONObject so you would construct one with it.
JSONObject object = new JSONObject(YOUR_STRING_OF_JSON);
Then you can access it with different get methods depending upon your expected type.
JSONArray results = object.getJSONArray("result"); // This is the node name.
String status = object.getString("status");
for (int i = 0; i < results.length(); i++) {
String resultStatus = results.getJSONObject(i).getString("status");
String type = results.getJSONObject(i).getString("type");
Log.w("JSON Result #" + i, "Status: " + resultStatus + " Type: " + type);
}
You need to surround it with a try/catch because JSON access can throw a JSONException.
Try re-factoring via a forEach loop
var testData =
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
};
var output = new Object;
var resultSet = new Object;
resultSet = testData.result;
resultSet.forEach(function(data)
{
theStatus = data['status'];
theType = data['type']
output[theType] = theStatus;
});
console.log( output['data1'] );
If you've got your models setup to mirror that data set, then you can let GSON (https://code.google.com/p/google-gson/) do a lot of your work for you.
If you want a bit more control, and want to parse the set yourself you can use JSONObject, JSONArray. There's an example of parsing and assembling a json string here: Android create a JSON array of JSON Objects

Extracting all values from nested JSON

I am fairly new to JSON parser and I am trying to extract all data set from "sizes" tag i.e extracting values (small, yes, xsmall, NO, Medium and yes) from the JSON file in a complex nested loop but doesn't work. I am using GSON to parse the JSON file and using JAVA as programming language
Here how the JSON file looks like in general
{ response: "ok",
prodinfo: {
sizes: [
{ size:"small",
available: "yes"
},
{ size:"xsmall",
available: "No"
},
{ size:"Medium",
available: "yes"
}
]
}
}
This is what i did
int array = jsonParser14.parse(json14).getAsJsonObject().get("ProdInfo").getAsJsonObject().getAsJsonArray("sizes").size();
JsonArray sizes = (JsonArray) jsonParser15.parse(json15).getAsJsonObject().get("ProdInfo").getAsJsonObject().getAsJsonArray("sizes");
for (int i = 0; i <= array; i++) {
String size = sizes.get(i).getAsString();
System.out.println("data extracted are: " + size);
}
Your help will be appreciated.
Thanks
I usually treat this by making a public class with required fields :
public class ProdSize {
public String size;
public String available;
}
public class ProdInfo {
public ProdSize[] sizes;
}
public class Message {
public String response;
public ProdInfo prodinfo;
}
And then I just have to do this in gson :
Gson gson = new GsonBuilder().create();
Message mess = gson.fromJson(theJsonString, Message.class);
Then, I don't have any loop to do to parse the JSON. I directly have my sizes in
mess.prodinfo.sizes
For example you can print them like this
for (int i=0; i<mess.prodinfo.sizes.length; i++) {
ProdSize size = mess.prodinfo.sizes[i];
System.out.println("Size " + size.size + " -> " + size.available);
}
Something like:
var sizes = json.prodinfo.sizes;
for (item in sizes) {
if (sizes.hasOwnProperty(item)) {
var isAvailable = sizes[item].available;
alert(isAvailable);
}
}​
Example here: http://jsfiddle.net/nG88B/3/
Edit:
Looks like you need to parse the JSON first. In which case (if it's valid) you can do:
var obj = JSON.parse(jsonStr);

Categories

Resources