How to parse JSON object in Java: - java

I am trying to parse to JSON object in java. I am posting json key value object using dojo.xhrPost() method as shown below:
dojo.xhrPost({
url: /esturl/,
handleAs : "text",
content : {INST1 : {"0001" : "aa"},
INST2 : {"0002" : "bb"},
INST3 : {"0003" : "cc"}},
load : load(data),
error : error
});
Now I am reading this post data from request context:
Map<String, String[]> paramMap = requestContext.getParameterMap();
when I am printing this in loop:
Iterator it = paramMap.entrySet().iterator();
while(it.hasnext()){
Map.entry pairs = (Map.Entry) it.next();
System.out.println(pairs.getKey());
System.out.println(pairs.getkValue());
}
this returns me :
INST1
[Ljava.lang.String;#1b4cef
INST2
[Ljava.lang.String;#5801d
like wise, but I should be getting values like
INST1 : {"0001" : "aa"}, INST2 : {"0002" : "bb"}, INST3 : {"0003" : "cc"}}, any guidance would be highly appreciated.
Update
When I try to get value of one parameter using
String[] X = requestContext.getParameters{"INST1"};
if (X != null){
System.out.println(X.length);
System.out.println(X[0]);
System.out.println(X[0].length);
}
then am getting :
1
[object Object]
[object Object]
Q Now how can I get actual values of Object like INST1 : {"0001" : "aa"} instead of [object Object] ?

you can use this modified JSONObject class, pass the raw JSON code through the constructor or create (new object and assign JSON content later..) and use built-in get methods. view full javadoc here.

as given in the dojo documentation here the object which you set up will be read as name1=value1. So may be in your case the variables are being passed like INST1=0001,INST1=aa.
You can try to make the syntax of 'content' on these lines - INST1 : '{"0001" : "aa"}' or
INST1 : "{\"0001\" : \"aa\"}" so that INST1 has 1 unambiguous value

Related

AWS textract Extract the meta-data and confidence score

Hi all i have extracted the document meta-data from AWS texttract Asynchronous call using java SDK but the meta-data is segregated into multiple blocks and it's huge.
How to extract the confidence score, value and its field name separately using java code i want to extract result something like below:
[{
"Field" : "FirstName",
"Value" : "XXXXX",
"confidence Score" : "98.88"
},
{
"Field" : "LastName",
"Value" : "XXXXX",
"confidence Score" : "65.98"
}]
Could anyone please suggest how to extract the field,value and its confidence score from aws texttract document meta-data?
anyone having any idea on this?
AWS has provided an example for mapping key and value pairs in python. You can use this code to understand the logic and come up with your own code in JAVA.
Source: https://docs.aws.amazon.com/textract/latest/dg/examples-extract-kvp.html
I have just begun with AWS Textract too in Java and wow what a great tool ! I have included code in my answer at this link if you would like to take a look :)
It extracts the keys and values. I suggest you create a model with Key, Value and confidence scores and then create an object for each key value pair
public static ArrayList<KVPair> getKVObjects(List<Block> keyMap, List<Block> valueMap, List<Block> blockMap ) {
ArrayList<KVPair> labelValues = new ArrayList<>();
Block value_block;
for (Block key_block : keyMap) {
value_block = findValueBlock(key_block, valueMap);
String key = getText(key_block, blockMap);
Float top = value_block.getGeometry().getBoundingBox().getTop();
Float left = value_block.getGeometry().getBoundingBox().getLeft();
Float confidenceScore = value_block.getConfidence();
Optional<KVPair> label= (labelValues.stream().filter(x-> x.getLabel().equals(key)).findFirst());
Property property = new Property();
property.setValue(getText(value_block, blockMap));
property.setLocationLeft(left);
property.setLocationTop(top);
property.setConfidenceScore(confidenceScore);
if(label.isPresent()){
label.get().setProperties(property);
}else{
KVPair KVPair = new KVPair();
KVPair.setLabel(key);
KVPair.setProperties(property);
labelValues.add(KVPair);
}
}
return labelValues;
}
AWS-Textract-Key-Value-Pair Java - thread "main" java.lang.NullPointerException

JAVA: Save data in JSON [duplicate]

This question already has answers here:
JSONObject : Why JSONObject changing the order of attributes [duplicate]
(3 answers)
Closed 7 years ago.
When you add data in JSONObject it will store in it's own way.
Here is the Example of what i am trying to convey.
JSONObject obj = new JSONObject();
obj.put("metricname", "splunk-ui");
obj.put("timestamp", 1234567890);
obj.put("value",34);
System.out.println(obj);
Above code snippet will give below output.
{
"metricname": "splunk-ui",
"value": 34,
"timestamp": 1234567890
}
Here is the Problem :-
I add data in this sequence :- metricname , timestamp , value
This is the display sequence :- metricname , value , timestamp
So , how do i enforce my data adding sequence in JSONObject ??
FYI :- Doing this is mendatory as i will pass this JSON object to another API which can scan data in metricname , timestamp , value only.
HERE I AM POSTING CODE SNIPPET WHICH I USED FOR SOLVING THIS PROBLEM :-
I have used GSON library and this link to make this code work.
GSON Documention
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("metric", "mihirmonani");
jsonObject.addProperty("timestamp", 1346846400);
jsonObject.addProperty("value", 14);
JsonArray jArray = new JsonArray();
JsonObject jObject = new JsonObject();
jObject.addProperty("host", "splunk");
jObject.addProperty("host1", "splunk1");
jsonObject.add("tags",jObject);
System.out.println(jsonObject);
You can't with a JSONObject the only way to keep the order is using a JSONArray
[
{"name" : "metricname", "value" : "splunk-ui"},
{"name" : "value", "value" : 34},
{"name" : "timestamp", "value" : 1234567890}
]
Short answer: you can't. JSONObject uses a HashMap internally, which returns values depending on the order of the hash code.
You could use JSONWriter to write the values explicitly.
EDIT: To clarify, as Manu pointed out, you cannot retrieve the order after the values have been put in the JSONObject. My suggestion was to not put the values in the JSONObject to begin with, but use JSONWriter to write the values directly.

how to retrive nested document and arrays values in elasticsearch

I have a following document
{
"_index" : "Testdb",
"_type" : "artWork",
"_id" : "0",
"_version" : 1,
"found" : true,
"_source":{"uuid":0,"ArtShare":{"TotalArtShares":0,"pricePerShare":0,"ArtworkUuid":12,"AvailableShares":0,"SoldShares":0},"StatusHistoryList":[{"ArtWorkDate":"2015-08-26T13:20:17.725+05:00","ArtworkStatus":"ACTIVE"}]}
}
i want to access/retrieve the value of ArtShare and its attributes and values of array StatusHistoryList
i am doing like this
val get=client.prepareGet("Testdb","artWork",Id.toString())
.setOperationThreaded(false)
.setFields("uuid","ArtShare","StatusHistoryList"
)
.execute()
.actionGet()
if(get.isExists())
{
uuid=get.getField("uuid").getValue.toString().toInt
//how to fetch `artShare` whole nested document and array elements `StatusHistoryListof`
}
UPDATE
if i do this
val get=client.prepareGet("Testdb","artWork",Id.toString())
.setOperationThreaded(false)
.setFields("uuid","ArtShare","StatusHistoryList"
,"_source","ArtShare.TotalArtShares")
.execute()
.actionGet()
if(get.isExists())
{
uuid=get.getField("uuid").getValue.toString().toInt
var totalShares= get.getField("ArtShare.TotalArtShares").getValue.toString().toInt
}
then following exception thrown
org.elasticsearch.ElasticsearchIllegalArgumentException: field [ArtShare] isn't a leaf field
at org.elasticsearch.index.get.ShardGetService.innerGetLoadFromStoredFields(ShardGetService.java:368)
at org.elasticsearch.index.get.ShardGetService.innerGet(ShardGetService.java:210)
at org.elasticsearch.index.get.ShardGetService.get(ShardGetService.java:104)
at org.elasticsearch.action.get.TransportGetAction.shardOperation(TransportGetAction.java:104)
at org.elasticsearch.action.get.TransportGetAction.shardOperation(TransportGetAction.java:44)
at org.elasticsearch.action.support.single.shard.TransportShardSingleOperationAction$ShardTransportHandler.messageReceived(TransportShardSingleOperationAction.java:297)
at org.elasticsearch.action.support.single.shard.TransportShardSingleOperationAction$ShardTransportHandler.messageReceived(TransportShardSingleOperationAction.java:280)
at org.elasticsearch.transport.netty.MessageChannelHandler$RequestHandler.doRun(MessageChannelHandler.java:279)
at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:36)
please guide me how to fetch these values
Yeah Actually the problem is that you have mentioned both "ArtShare" and "ArtShare.TotalArtShares" in the fields array. So it throws exception as you have already retrieved complete ArtShare object.
So please mention the fields that you want, If you want specified nested values then no need to access complete parent object.
Try this:
val get=client.prepareGet("Testdb","artWork",Id.toString())
.setOperationThreaded(false)
.setFields("uuid","StatusHistoryList",
"ArtShare.TotalArtShares")
.execute()
.actionGet()
if(get.isExists())
{
uuid=get.getField("uuid").getValue.toString().toInt
var totalShares= get.getField("ArtShare.TotalArtShares"
}
And if you want complete "ArtShare" object then simply write :
val get=client.prepareGet("Testdb","artWork",Id.toString())
.setOperationThreaded(false)
.setFields("uuid","ArtShare","StatusHistoryList"
)
.execute()
.actionGet()
if(get.isExists())
{
uuid=get.getField("uuid").getValue.toString().toInt
//how to fetch `artShare` whole nested document and array elements `StatusHistoryListof`
}

How to access nested element of mongo query result using Java and R?

I am using Java and R to fetch data from my database and implement prediction. My json in mongodb is like:
{
"Server" : [
{
"deviceName" : "NEWSCVMM",
"availability" : 100,
"osVersion" : "6.3.9600",
"averageResponseTime" : 0.422,
"useswapmemory" : "983040",
"freeswapmemory" : "983040",
"model" : "Virtual Machine",
"numberOfCpu" : "1",
"vendor" : "Microsoft Corporation",
"vmList" : [ ],
"macadd" : [ ],
"cpuInfo" : "Intel(R) Xeon(R) CPU X5670 # 2.93GHz",
"memory" : "6188596",
"serialNo" : "00252-00000-00000-AA228",
"cpuUtilization" : 0,
}]
}
I want to access cpuUtilization from that json. I tried to access nested values using (.) but get result as NULL. I also tried to execute same on R shell but get result as NULL.
Here is what I have tried so far:
c.eval("query <- dbGetQuery(db,' mycollection','{\"hostId\":\"0.0.0.0\",\"windowsServer.cpuUtilization\":{\"$ne\":\"null\"},\"runtimeMillis\":{\"$ne\":\"null\"}}')");
c.eval("date <- query$runtimeMillis");
c.eval("host_id <- query$hostId");
c.eval("cpu <- query$Server.cpuUtilization");
c.eval("all_data<-data.frame(cpu,date)");
c.eval("training<- all_data");
c.eval("rf_fit<-randomForest(cpu~date,data=training,ntree=500)");
c.eval("new <- data.frame(date="+my_predicted_date+ ")");
c.eval("predictions<-predict(rf_fit,newdata=new)");
REXP memory_predictions= c.eval("predictions");
How do I access nested elements on either R shell or using java?
Dot notation should work in Java, I have been using it for quite a while now.
Check your code carefully, there might be a slight mistake somewhere.
Can you please post a part of your code here? I can then take a look and comment.
Here is what I normally do -
Lets say my document is like this -
{_id:0, start : {x:10, y:50}, end : {x:20, y:100}}
{_id:1, start : {x:20, y:50}, end : {x:30, y:100}}
{_id:2, start : {x:30, y:50}, end : {x:40, y:100}}
If I want to query based on "x" value in start field, I would write something like this:
MongoClient client = new MongoClient();
DB db = client.getDB("YourDBNAME");
DBCollection collection = db.getCollection("YOURCOLLECTIONAME");
QueryBuilder builder = QueryBuilder().start("start.x").greaterThan("20");
DBCursor cur = collection.find(builder.get());
while(cursor.hasNext())
{
System.out.println(cursor.next());
}
Compare this code snippet with yours and see. You should get it working fine.
Let me know if this helps or you need more help on this.

Get the values of posted array in servlet

var schedule = [];
var data = {
'user_id' : '12',
'day_of_week' : 'Monday',
'when' : 'start',
'modified' : 'true'
}
schedule.push(data);
var data = {
'user_id' : '13',
'day_of_week' : 'Tuesday',
'when' : 'end',
'modified' : 'false'
}
schedule.push(data);
// schedule would have two objects in it
I am posting array to servlet using jquery ajax post request as below .
data : {'myData':schedule},
url :"./myController",
Now how can I get array of objects and literate to get all the values? Each array object has string, long and boolean type values. How can I get all the values by iterating?
May be you can try this
json.getJSONObject("myData").getString("your_values");

Categories