Serializing as javascript object - java

I am working on a Spring MVC and I want to insert javascript into the html output for analytics purpose. I am only partially familiar with serialization but I figured it does the job nicely rather than manually constructing a string containing javascript.
Would it be possible to generate something the following snippet? Any pointers would be great!
"emd" : new Date('6/6/2014')
Update:
I need to output a javascript object which has many fields which may be complex. Hence, on the backend I am gathering all the data into java beans with all the information and I plan to use Jackson mapper to convert to string that I can just output through JSP.
Generating the above snippet does not seem straightforward though, not sure if it is even possible. For context, the rest of that javascript looks something like this.
Analytics.items["item_123"] = {
//ratings and reviews
"rat" : a.b, //the decimal value for the rating
"rev" : xxxx, //integer
//list of flags that indicate how the product was displayed to the customer
//add as needed...tracking code will pick up flags as needed when they are available
"dec" : ["mbe", "green", "recycled"],
//delivery messaging
"delivery" : {
"cd" : new Date() //current date
"offers" : [{
"type" : "abcd"
"emd" : new Date('6/6/2014'),
"weekend" : true
}
]
},
};

JSON.stringify should do the trick. It will be built into your browser, unless you're using a very old browser, in which case you can use a polyfill.

Related

Read JSON with special character in keys using apache velocity

I have a JSON which has an attribute with its List type. Can someone help me on how to read the value in Apache Velocity template? Following is an example of JSON. The challenge is to read the list of University from JSON and iterate through it.
{
"StudentName":"XYZ",
"List<Univesity>": [
{
"Name": "NYU",
"City": "NY",
"Country":"US",
} ]
}
The solution is dependent upon the JSON library you use, but for many of them, the following code should work:
#set( $universities = $document.get('List<University>') )
#foreach( $university in $universities )
... do something ...
#end
The main point to note here is that you can call any Java method on the object you get.
Also, if the security uberspector is not present, for debugging purposes you can display the Java class name of any object in the context, for instance: $document.class.name should display, in your case, something like com.fasterxml.jackson.databind.node.ObjectNode.

Which is the proper way to work with complex types (lists and objects) in Jaspersoft?

Please consider a MongoDB collection with the following document:
"_id": "clientsInfo"
"data": {
"clientsList" : [
{
"name" : "Mike",
"country" : "USA"
},
...
]
}
After setting the DataSet and defining the Query like this...
{
collectionName:'projectA',
findQuery: {
'_id':'clientsInfo',
},
findFields: {
'_id':0,
'data.clientsList':1
},
}
...I am able to display the first item of the fetched array (java.util.List type) in JasperSoft Studio inside a Text Field using the following expression:
$F{data.clientsList}.get(0)
But, considering that I would like to exhibit the whole data in a Name/Country Table...
Question1: How could I access any of the dictionary fields? Trying get method I obtain The method get(String) is undefined for the type Object. error. However, knowing that the object is an instance of com.mongodb.BasicDBObject it should have that method inherited (See doc).
I have also tried to cast object to org.json.JSONObject but then I get net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression for source text: (JSONObject)$F{data.clientsList}.get(0) error.
Question2: Let's suppose we have already solved first question... How can I iterate the list to access not only the first item but all of them according to the array length? Is it possible to use for-loop sentence inside the JasperSoft Expression Editor? (if-then-else seems to be available)
Thanks in advance, Any clue that point me in the right direction will be appreciated.
Just in case someone was in the same situation as I was, I must say this whole approach was wrong.
It's not about making a simple query which returns big block of complex data formatted as an object or list of objects and then manipulate it with JasperSoft Studio. Instead, what I had to do was design a more elaborated query which returns the simple fields I wanted to use straightforward. How to do this? By using Aggregation Framework.
So, by changing this...
{
collectionName:'projectA',
findQuery: {
'_id':'clientsInfo',
},
findFields: {
'_id':0,
'data.clientsList':1
},
}
...for this...
{
runCommand: {
aggregate : 'projectA',
pipeline : [
{'$match': {'_id':'clientsInfo'}},
{'$project': {'data.clientsList': 1}},
{'$unwind': '$data'},
{'$unwind': '$data.clientsList'}
]
}
}
...is how I get name and country fields in order to use them in Text Fields, Tables, ...etc.

ElasticSearch Adding field in JSON before indexing

[This is my first post, please excuse me if I'm doing something wrong! (also sorry for my bad English)]
I'm try to develop a Mapper/Plugin for elasticsearch (in Java) that analyze some specified fields of JSON and add another field with the result of the analysis before storing and indexing the data.
EG:
I start with this popular JSON:
{
"tweet" {
"user" : "kimchy",
"message" : "This is a tweet!",
"postDate" : "2009-11-15T14:12:12",
"priority" : 4,
"rank" : 12.3
}
}
And, before the indexing, I Want it like:
{
"tweet" {
"user" : "kimchy",
"message" : "This is a tweet!",
"postDate" : "2009-11-15T14:12:12",
"priority" : 4,
"rank" : 12.3
"IsKimchy" : "Yes"
}
}
Here I suppose to read the field "user" and if the user is Kimchy I create another field that contain "Yes".
how can I analyze a field (using java) like this before the indexing?
As I know I can copy the content of a field in an other using Copy_to, so I can work only on a field, maybe it can help?
I had finally found a solution for my problem, I'll post it here, hope to help someone else!
the best solution for me (in Terms of Speed and integration) was a Custom mapper!
I had use this demo code https://github.com/dadoonet/elasticsearch-mapper-demo to implement my mapper class that analyze the Json Faster than scripting and add a custom field in record!
Cheers!

Dynamic Creation of JSON Object Arrays

This is a continuation of my work on a gradebook program. I have been posting my questions related to JSON and connecting two applications to StackOverflow because I've been having a really difficult time with that part.
I have been attempting to create an HTTP POST request that uses JSON for the purpose of sending information from a Java gradebook application to a Rails web-based application that displays those grades in the form of a report to students.
Ultimately, I want to send more than just one student's information. Furthermore, each student might have anywhere from 0 to 50 assignments, descriptions of the assignments, as well as grades for those assignments. On top of that there will be multiple classes/courses of students. All this information needs to be "read in" to the JSON object. Does anyone have any suggestions about how I could modify this code so that I could send all that data?
The farthest that I was able to take the JSON-related part of code is shown below. However, that code needs to be modified as the following questions suggest.
1. How do I create the array of JSON objects dynamically rather than how it is shown below (since the courses, students, and grades will vary and be read in from the Java program)?
2. How do I synthesize/combine the three JSON arrays of objects below to make it work? My idea is that I write the array of course objects then somehow embed the array of student objects as part of each course object, then somehow embed the array of grade objects as part of each student object.
{‘JSONArrayOfCourseObjects’ : [{‘courseID’ : ‘Botany101FallSemester’, ‘courseInstructor’ :
‘Mr. Smith’}, {‘courseID’ : ‘Physics101FallSemester’, ‘courseInstructor’ : ‘Mrs. Newton},
etc.]}
{‘JSONArrayOfStudentObjects’ : [{‘Name’ : ‘John Doe’, ‘StudentID’ : ‘12345678’, ‘Address’ :
‘1234 Main Street’}, {‘Name’ : ‘Don Corleone’, ‘StudentID’ : ‘87654321’, ‘Address’ :
‘121 Walberry Ave’}, etc.]}
{‘JSONArrayOfGradeObjects’ : [{‘nameOfAssignment’ : ‘Irrigation Homework 1’,
‘dateOfAssignment’ : ‘Sept 1, 2014’, ‘categoryOfAssignment’ : ‘Homework’},
{‘nameOfAssignment’ : ‘Test 1’, ‘dateOfAssignment’ : ‘Sept 14, 2014’, ‘categoryOfAssignment’ :
‘Test’}, etc.]}
JSONlib is the simplest Java API out there for generating quick and dirty JSON. It has everything you need to build up the object and convert it to text. If you need something more powerful, there's GSon and Jackson.
Here are some samples. This example is in Groovy so it's not copy and pasteable, but it shows you how to use it:
def array = new JSONArray()
new File("/path/to/grades/files").eachFile { file ->
String rawJson = file.text
JSONObject obj = (JSONObject ) JSONSerializer.toJSON( rawJson )
array = array.element(obj)
})
println array.toString(5) //Use 5 character indentation

how to pass java beans to jsp page for jqQrid to display using json?

we are trying to use jqGrid with our jsp front end and java back end.
this page is displaying a grid of contacts :
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
datatype: 'json',
url:'gridContactDrv.jsp',
mtype: 'GET',
height:300,
width:600,
colNames:['First Name','Last Name', 'Company', 'Primary Phone','Email'],
colModel :[
{name:'firstname', index:'firstname', width:100},
{name:'lastname', index:'lastname', width:100 },
{name:'company', index:'company', width:100},
{name:'phone', index:'phone', width:100 },
{name:'email', index:'email', width:200}
],
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
sortname: 'lastname',
sortorder: 'desc',
viewrecords: true
});
});
gridContactDrv.jsp calls a search function which return a Vector of ContactBeans. In our current (old) way, we loop through the vector, hook out the 5 fields in each bean and contruct a HTML table.
now we want to use json and i can't figure out how to contruct a valid json (obect? array?) to pass to the grid.
Enumeration e = resultVector.elements();
while (e.hasMoreElements())
{
ContactBean c = ContactBean((ContactBean)e.nextElement());
c.getCompany()
c.getFirstName() etc etc and what to do?
}
btw the ContactBean has many other data members but we are only displaying the 5 fields.
can someone give me some pointers to start? i have searched for a few days and feel like not getting anywhere.
Have you looked at the JSONWriter class from json.org?
Quoting from the API docs:
new JSONWriter(myWriter)
.object()
.key("JSON")
.value("Hello, World!")
.endObject();
which writes
{"JSON":"Hello, World!"}
You need to:
Configure your jqGrid instance to expect JSON data
Have something (servlet?) on back-end that would handle JSON request. You could, of course, output grid data as JSON in the same JSP that renders jqGrid but that would largely defeat the purpose (especially for large volumes of data if pagination is involved).
Use JSON library like json-lib to marshall your beans into JSON. I personally like XStream but there are many various implementations available.

Categories

Resources