I'm trying to make a dynamic jsp page based on the json.
For example, if my json is look like this:
{
'page1':'true',
'page2':'true',
'page3':'false'
}
In php, I could get my associative array easily by one line:
$data = json_decode($json_str);
Then I could access whichever that I wanted at the place I needed, (i.e)
If($data['page1'] == 'true')
echo #page link#;
But in jsp, it doesn't goes so easily because it don't have much documents like php. I find the gson but still not sure. how to use it to achieve it.
Please give me some example that I could turn json to associative array, then get and access it in jsp.
A Java Map is an associative array. You can ask Gson to deserialize your json input with this:
Map<String,String> map = new Gson().fromJson(inputJson, new TypeToken<Map<String,String>>() {}.getType());
Example code:
package net.sargue.gson;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.Map;
public class SO36859440 {
public static void main(String[] args) {
String inputJson = "{\n" +
" 'page1':'true',\n" +
" 'page2':'true',\n" +
" 'page3':'false'\n" +
"}";
Type type = new TypeToken<Map<String, String>>() {}.getType();
Map<String,String> map = new Gson().fromJson(inputJson, type);
System.out.println(map.get("page2"));
System.out.println(map.get("page3"));
}
}
The output is:
true
false
Then, your question is about converting it in JSP. Well, best practices for JSP advice you to move this kind of processing to a Servlet that acts as a controller and passes attributes to the JSP in order to build the view. You can put code directly on the JSP using <% ... %> but I highly discourage you to do so. But that's an entirely different question.
Related
So Im using the Mailer Package in flutter https://pub.dev/packages/mailer, and its great and everything but one problem im facing is that i want to pass a complex HTML template/file to the Mailer's package "...html" parameter instead of a simple one. The way i wanna approach this problem is through creating a separate file (heard it could be a dart file and write HTML in it P.S. please show me how), and then pass this file to the "...html" parameter in the Mailer package. Please tell me how is this possible in flutter. My Code
In this case, using the raw String definition it's recommended:
final String html = '''
very long html here
'''
final Message = Message()
..html = html;
An even better approach would be to define the HTML template in a separate file:
//html_template.dart
library html_template;
final String html = '''
<html></html>
'''; // very long html template definition
And import it when required:
import './html_template.dart' as Template;
void main() {
final Message = Message()..html = Template.html;
}
The problem is as follows: I want to handle a POST request with JSON body. The body consists of an array of JSON Objects, without further nesting, i.e. simple HashMaps. All of these objects represent JSON-serialized domain classes from an Android Application, which will have their counterpart in my Grails app. I am thinking of parsing the JSON body, iterating through every element and saving each node as its corresponding domain class instance.
a) How should I save the instance? I am quite new to Grails/Groovy so please excuse any huge mistakes. Code so far is
public static Object JSONArray2Instances(String json, Class type) {
def slurper = new JsonSlurper()
def result = slurper.parseText(json)
//we only want to parse JSON Arrays
if (!(result instanceof JSONArray))
return null
result.each {
def instance = it.asType(type)
// now I need to save to domain class!
}
}
b) where do I place the corresponding code? Currently it is in /grails-app/src/groovy. Where do the tests go? (Since it is not a 'real' Grails component)
c) Is an intermediate command object more appropriate?
Your code should go in to the controller which is handling the request. Please take a look at
gson-grails plugin which has examples of how to serialize and deserialze objects and map them to domain objects. Please take a look at the grails basics where they talk about the conventions used in the grails application and the layout. There are good examples at grails site. Hope this helps
I solved my problem as follows, based on help provided by the comment from allthenutsandbolts. : (Grails-Gson plugin was not needed)
Let N2696AdminAction be the name of a Domain Class
in my controller:
class N2696AdminActionController extends RestfulController{
static responseFormats = ['json', 'xml']
def JSONHandlerService
N2696AdminActionController() {
super(N2696AdminAction)
}
#Override
#Transactional
def save(){
if (request!=null)
JSONHandlerService.instancesfromJSON(request.JSON)
}
}
then I delegate persisting to my service as follows
class JSONHandlerService {
def instancesfromJSON(Object request){
//we only want to parse JSON Arrays
if (!(request instanceof JSONArray))
return null
request.each {
def domainClass = Class.forName("${it.type}",
true, Thread.currentThread().getContextClassLoader())
def newDomainObject = domainClass.newInstance(it)
newDomainObject.save(failOnError:true, flush:true, insert: true)
}
}
}
type is a Json attribute which holds the full (package inclusive) name for my class. This way, I can save to multiple Domain Classes with the same POST request.
I have a grails object that I am converting using def json = object as JSON. After I have it converted I want to add one more property called pin to the JSON which looks like the following.
[location:[lat:23.03, lon:72.58]]
Only way to do this so far seems like following
Serialize the DomainClass to JSON using grails.converters.json
Convert the JSON to string
Create JSONBoject using the string from Step 2
Add the property
Convert it back to String
Any other way to do this using grails.converters.json? I have tried using Gson but I do not want to go that route because I am getting many Circular Reference Errors
Try this:
domainInstance.properties + [pin: pinInstance] as JSON
I recently needed to do a similar thing. Some caveats:
This is using Grails 2.4.5
I use MongoDB as a backend. As such, I created an object marshaller for MongoDB domain classes. It is printed below, and you can wrap a similar marshaller for your domain class(es):
Marshaller:
class MongodbObjectMarshaller implements ObjectMarshaller<JSON> {
#Override
boolean supports(Object o) { return o?.properties?.dbo }
#Override
void marshalObject(Object obj, JSON converter) throws
ConverterException {
Map propertiesToOutput = obj.properties.dbo
propertiesToOutput.remove("_id") //don't print org.bson.types.ObjectId
propertiesToOutput.remove("version") //don't print gorm verson column
converter.build {
_id obj.id.toString()
propertiesToOutput.each{ entry ->
"$entry.key" entry.value
}
}
}
}
What that marshaller does, it allow in JSON output any of the domain class's properties. obj.properties.dbo is special to MongoDB, but for a regular domain class, you can just grab the properties and exclude the ones you don't need.
Then in my controller, this works:
domainInstance.pin = [location:[lat:23.03, lon:72.58]]
def content = tacticalCard as JSON
because my marshaller now picks up the pin property and prints it.
Im pretty new to Java and Im searching the Internet for a simple way to load an external csv into JavaFX TableView.
I was able to parse the CSV into an array but I dont know how I have to handle it now. Then I was playing with the DataFX library. But again wasnt able to pass the parsed csv into my table.
I think I dont really understand ObservableLists here which I believe is kind of necessary? Do you know a good tutorial or could you explain what the next steps would be after parsing the file?
thx
Edit: That's what I did
import javafx.application.Application;
import javafx.scene.SceneBuilder;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
import org.javafxdata.datasources.reader.FileSource;
import org.javafxdata.datasources.provider.CSVDataSource;
public class CSVTableSample extends Application {
#SuppressWarnings("unchecked")
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("Test App");
// Just loading the file...
FileSource fs = new FileSource("test.csv");
// Now creating my datasource
CSVDataSource dataSource = new CSVDataSource(
fs, "order-id", "order-item-id");
#SuppressWarnings("rawtypes")
TableView table1 = new TableView();
TableColumn<?, ?> orderCol = dataSource.getNamedColumn("order-id");
TableColumn<?, ?> itemCol = dataSource.getNamedColumn("order-item-id");
table1.getColumns().addAll(orderCol, itemCol);
table1.setItems(dataSource);
stage.setScene(SceneBuilder.create().root(table1).build());
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
eclipse says for table1.setItems(dataSource);
The method setItems(ObservableList) in the type TableView is not applicable for the arguments (CSVDataSource)
There is a sample solution here for a tab delimited file.
A csv file could handled similarly.
The sample works by declaring the type of the the TableView as TableView<ObservableList<StringProperty>> such that each row in the TableView is an ObservableList of string properties where each property represents a field in the csv file. The TableView's items list is a list of such lists. cellValueFactorys set for each column extract the correct cell value for that column from the ObservableList<StringProperty> backing that cell's row.
The method setItems(ObservableList) in the type TableView is not
applicable for the arguments (CSVDataSource)
change your line
table1.setItems(dataSource);
to
table1.setItems(dataSource.getData());
Example Code Using DataFX :
DataSourceReader dsr1 = new FileSource("your csv file path");
String[] columnsArray // create array of column names you want to display
CSVDataSource ds1 = new CSVDataSource(dsr1,columnsArray);
TableView tableView = new TableView();
tableView.setItems(ds1.getData());
tableView.getColumns().addAll(ds1.getColumns());
if you want to do it in standard javafx way : Look Here
We have used JSO for our JSON parsing in GWT client side. Now, we need to convert our Java objects to JSON string. I just wanted to understand, how we can achieve this? JSO overlay types was used for JSON parsing. Can it also be used to create a JSON request string or do we have to go by some other means?
Generating a JSON object in JavaScript is pretty simple. You can do it like this:
var obj = { "var1": "hello", "var2": "world" };
this will generate a JSON object with two varibles ("var1" and "var2") with their values ("hello", "world").
The Object can be converted into a String (for sending purposes) with the JSON.stringify(jso); method.
Generating JSON data from the java code isn't possible (well not with a usefull result) since all varibles are optimzed to single Strings, so applying this method wouldn't hava a usefull result (if even possible).
If you have already a JSO object (generated with something like safeeval). You can edit your varibles there, like this:
public final native void newValue(String newValue) /*-{
this.ValueName = newValue;
}-*/;
If you then want the object as string you have to define the following method in your JSO class:
public final native String returnAsString () /*-{
return JSON.stringify(this);
}-*/;
or use this in you Java class: String s = (new JSONObject(jso)).toString();.
This way you can edit your original intput data and send the original object back to the server.
BR