How to parse AEM DAM JSON InputStream and create JSON Object

放肆的年华 提交于 2019-12-11 16:58:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!