我是初学者。我有一个用syso打印jsonText的值。如何将此值保存在变量中,以连接for的长度的所有值。这是我的代码。谢谢。
for(int i=0;i<nodes.getLength();i++) {
Element element = (Element)nodes.item(i);
Map<String, String> obj=new LinkedHashMap<String, String>();
obj.put("category",getElementValue(element,"category"));
obj.put("title",getElementValue(element,"title"));
obj.put("date",getElementValue(element,"pubDate"));
obj.put("description",getElementValue(element,"description"));
obj.put("content",getElementValue(element,"content:encoded"));
StringWriter out = new StringWriter();
JSONValue.writeJSONString(obj, out);
String jsonText = out.toString();
System.out.println(jsonText);
}
答案 0 :(得分:0)
您可以使用StringBuilder来连接jsonText。
StringBuilder builder = new StringBuilder();
for(int i=0;i<nodes.getLength();i++) {
Element element = (Element)nodes.item(i);
Map<String, String> obj=new LinkedHashMap<String, String>();
obj.put("category",getElementValue(element,"category"));
obj.put("title",getElementValue(element,"title"));
obj.put("date",getElementValue(element,"pubDate"));
obj.put("description",getElementValue(element,"description"));
obj.put("content",getElementValue(element,"content:encoded"));
StringWriter out = new StringWriter();
JSONValue.writeJSONString(obj, out);
String jsonText = out.toString();
System.out.println(jsonText);
builder.append(jsonText);
}
答案 1 :(得分:0)
简单,
StringBuilder builder = new StringBuilder();
for(int i=0;i<nodes.getLength();i++) {
..... your existing code ....
builder.append(jsonText);
}
String finalData = builder.toString();
答案 2 :(得分:-2)
您可以在for循环之外创建一个全局变量:
String allStrings = "";
然后使用string1.concat(string2);方法:
allStrings = allStrings.concat(jsonText);