예를 들어 org.json library을 사용하여 JSON 문자열을 구문 분석 한 다음 구문 분석 결과에서 VelocityContext를 작성하면됩니다.
<html>
<body>
$name is $age years old and lives $address.streetAddress, ${address.city}.
<br/>
$name's friends:
<ul>
#foreach($friend in $friends)
<li>$friend.name, who is $friend.age years old</li>
#end
</ul>
</body>
</html>
당신은이 같은 JSON 문자열에 병합 할 수 있습니다 :
하자가 다음과 같은 템플릿이 있다고 당신이 어떤 루트 속성 아래 JSON 객체를 포장하려면
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.json.JSONObject;
public class JsonPublisher
{
protected VelocityEngine velocity;
public JsonPublisher()
{
// init velocity
// default resource loader is a file loader on the current directory
velocity = new VelocityEngine();
velocity.init();
}
public String publish(String templatePath, String jsonString) throws IOException
{
// translate json string to velocity context
// (we only need to convey the properties of the root object)
JSONObject jsonObj = new JSONObject(jsonString);
VelocityContext context = new VelocityContext();
for(String key : jsonObj.keySet())
{
context.put(key, jsonObj.get(key));
}
Writer writer = new StringWriter();
velocity.mergeTemplate(templatePath, "UTF-8", context, writer);
writer.flush();
return writer.toString();
}
public static void main(String args[])
{
try
{
String str = "{ \"name\": \"Alice\", \"age\": 20, \"friends\": "+
"[ { \"name\":\"Bob\", \"age\":21 }, { \"name\":\"Carol\", \"age\":19 } ], " +
"\"address\": { \"streetAddress\": \"100 Wall Street\", \"city\": \"New York\" } }";
String result = new JsonPublisher().publish("template.vm", str);
System.out.println(result);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
문맥, $json
라고 가정 해 봅시다. 그러면 더 간단합니다.
....
JSONObject jsonObj = new JSONObject(jsonString);
VelocityContext context = new VelocityContext();
context.put("json", jsonObj);
....
멋진 설명 답을 보내 주셔서 감사합니다. 쿼리가 있었으므로 JSON이 큰 경우 변환 속도가 느려 집니까? –
JSON 크기가 큰 경우 메서드가 적절하지 않을 수 있지만 큰 볼륨이 브라우저에 업로드되지 않으므로 HTML이 적절하지 않을 수 있습니다. 그것은 당신이 * 큰 *이라고 부르는 것에 정말로 달려 있습니다. 특정 크기 이상에서는 스트림 처리 (라인 파싱 + 게시, à la * sed/awk *) 만 관련되어 있으며 매우 자주 작성하는 것이 가장 좋습니다. –