我一直在尝试使用 Jackson 库(v.1.7.4,这是我唯一可以用于此项目的库)在 Java 中构建一个 jsTree 接受的格式的 JSON 字符串 ( https://www.jstree.com/docs/json/ ) .我只关心“文本”和“子项”属性。问题是,我没有得到一个可行的递归方法来这样做。
如果我有一个像这样的简单树:
Tree<String> tree = new Tree<String>();
Node<String> rootNode = new Node<String>("root");
Node<String> nodeA = new Node<String>("A");
Node<String> nodeB = new Node<String>("B");
Node<String> nodeC = new Node<String>("C");
Node<String> nodeD = new Node<String>("D");
Node<String> nodeE = new Node<String>("E");
rootNode.addChild(nodeA);
rootNode.addChild(nodeB);
nodeA.addChild(nodeC);
nodeB.addChild(nodeD);
nodeB.addChild(nodeE);
tree.setRootElement(rootNode);
我希望我的字符串是:
{text: "root", children: [{text:"A", children:[{text:"C", children: []}]}, {text:"B", children: [{text: "D", children: []}, {text:"E", children:[]}]}] }
我正在尝试使用 Jackson 的树模型构建 JSON 字符串。到目前为止,我的代码看起来像这样:
public String generateJSONfromTree(Tree<String> tree) throws IOException{
String json = "";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = new JsonFactory();
ByteArrayOutputStream out = new ByteArrayOutputStream(); // buffer to write to string later
JsonGenerator generator = factory.createJsonGenerator(out, JsonEncoding.UTF8);
JsonNode rootNode = mapper.createObjectNode();
JsonNode coreNode = mapper.createObjectNode();
JsonNode dataNode = (ArrayNode)generateJSON(tree.getRootElement()); // the tree nodes
// assembly arrays and objects
((ObjectNode)coreNode).put("data", dataNode);
((ObjectNode)rootNode).put("core", coreNode);
mapper.writeTree(generator, rootNode);
json = out.toString();
return json;
}
public ArrayNode generateJSON(Node<String> node, ObjectNode obN, ArrayNode arrN){
// stop condition ?
if(node.getChildren().isEmpty()){
arrN.add(obN);
return arrN;
}
obN.put("text", node.getData());
for (Node<String> child : node.getChildren()){
// recursively call on child nodes passing the current object node
obN.put("children", generateJSON(child, obN, arrN));
}
}
我尝试了一些变体,但到目前为止没有成功。我知道答案可能比我尝试的要简单,但我卡住了。也许停止条件不合适或逻辑本身(我的想法是尝试在下一次调用时重用 ObjectNode 和 ArrayNode 对象,以在下一个子节点上“插入”“children”元素(来自 json)树,所以它会向后构建,但最后我得到空变量)。
我的树和节点类基于以下内容:http://sujitpal.blogspot.com.br/2006/05/java-data-structure-generic-tree.html
最佳答案
这不是最好的方法,但它可以完成工作:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class TreeApp {
public String generateJSONfromTree(Tree<String> tree) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = new JsonFactory();
ByteArrayOutputStream out = new ByteArrayOutputStream(); // buffer to write to string later
JsonGenerator generator = factory.createJsonGenerator(out, JsonEncoding.UTF8);
ObjectNode rootNode = generateJSON(tree.getRootElement(), mapper.createObjectNode());
mapper.writeTree(generator, rootNode);
return out.toString();
}
public ObjectNode generateJSON(Node<String> node, ObjectNode obN) {
if (node == null) {
return obN;
}
obN.put("text", node.getData());
ArrayNode childN = obN.arrayNode();
obN.set("children", childN);
if (node.getChildren() == null || node.getChildren().isEmpty()) {
return obN;
}
Iterator<Node<String>> it = node.getChildren().iterator();
while (it.hasNext()) {
childN.add(generateJSON(it.next(), new ObjectMapper().createObjectNode()));
}
return obN;
}
public static void main(String[] args) throws IOException {
Tree<String> tree = new Tree<String>();
Node<String> rootNode = new Node<String>("root");
Node<String> nodeA = new Node<String>("A");
Node<String> nodeB = new Node<String>("B");
Node<String> nodeC = new Node<String>("C");
Node<String> nodeD = new Node<String>("D");
Node<String> nodeE = new Node<String>("E");
rootNode.addChild(nodeA);
rootNode.addChild(nodeB);
nodeA.addChild(nodeC);
nodeB.addChild(nodeD);
nodeB.addChild(nodeE);
tree.setRootElement(rootNode);
System.out.println(new TreeApp().generateJSONfromTree(tree));
}
}
关于java - 使用 Jackson 递归构建 JSON 字符串到 jsTree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33617570/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)