Java: serialize TreeModel, TableModel to JSON, and vice versa?
On the client side, a user specified input creates a unique TreeModel and TableModel.
This needs to be serialized to JSON for storage on MongoDB (stores JSON document directly).
The JSON needs to be parsed back into a TreeModel or TableModel which will be rendered again on the client side software.
Any library or existing codes which can faciliate t开发者_开发问答his?
TreeModel and TableModel are just interfaces without data therefore they cant be serialized. However when you talk about TreeModel implementation e.g. DefaultTreeModel you can serialize it to Json using Jackson POJO data binding
Jackson can do so in 5 minutes
You can iterate through the model's data and use jackson to generate the json. I.e.:
public static JsonNode getJsonNodeFromModel(DefaultTableModel model) {
ArrayNode jsonArray = MAPPER.createArrayNode();
for (int i = 0; i < model.getRowCount(); i++) {
ObjectNode jsonNode = MAPPER.createObjectNode();
String name = (String) model.getValueAt(i, 0);
String command = ((String) model.getValueAt(i, 1)).replace("\\", "\\\\");
jsonNode.put(model.getColumnName(0), name);
jsonNode.put(model.getColumnName(1), command);
jsonArray.add(jsonNode);
}
return jsonArray;
}
Test:
@Test
public void testMethod() {
Object[] columnNames = new Object[]{"Name", "Shell Command"};
Object[][] data = {
{"Open jsonlint.com", "open http://jsonlint.com"},
{"Open Escape/UnEscape Tool", "open http://www.freeformatter.com/javascript-escape.html"}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JsonNode jsonNode = CommandHelper.getJsonNodeFromModel(model);
assertEquals("Open jsonlint.com", jsonNode.get(0).get("Name").asText());
assertEquals("open http://jsonlint.com", jsonNode.get(0).get("Shell Command").asText());
assertEquals("Open Escape/UnEscape Tool", jsonNode.get(1).get("Name").asText());
assertEquals("open http://www.freeformatter.com/javascript-escape.html", jsonNode.get(1).get("Shell Command").asText());
}
精彩评论