问题
I have a requirement where-in I have to read the JSON file which exists in AEM DAM. So, I have created a query to read the JSON file in inputStream. With the below line of code, i could get the JSON file in Input Stream. Now, I need to know If there is any standard library to read the input stream and create the JSON Object?
InputStream is = asset.getOriginal().getStream();
回答1:
There are many libraries for serializing/deserializing JSON in java, the most notable is Google’s Gson: https://github.com/google/gson
I’ve used gson in all my AEM projects that require JSON manipulation. That does not mean you can’t use another library.
回答2:
As mentioned above there are many libraries like Google’s Gson, Jackson an etc. I think the below code snippet can help you,
public JSONObject getJsonFromFile(ResourceResolver resolver,String filePath){
JSONObject jsonObj=new JSONObject();
Resource resource= resolver.getResource(filePath);
try {
Node jcnode = resource.adaptTo(Node.class).getNode("jcr:content");
InputStream content=jcnode.getProperty("jcr:data").getBinary().getStream();
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new
InputStreamReader(content,StandardCharsets.UTF_8));
while ((line = br.readLine()) != null) {
sb.append(line);
}
jsonObj = new JSONObject(sb.toString());
}catch (RepositoryException | JSONException | IOException e) {
LOGGER.error(e.getMessage(),e);
}
return jsonObj;
}
来源:https://stackoverflow.com/questions/49121569/how-to-parse-aem-dam-json-inputstream-and-create-json-object