如何在Java中创建JSONArray [英] How create a JSONArray in java
问题描述
我有2个Java函数: listeFilesHdfs
返回存储在HDFS中的文件的列表,例如:
I have 2 java functions:
listeFilesHdfs
return a list of files that stored in HDFS, for example:
如果选中,存储在HDFS中的文件格式为JSON格式,例如:
If you remark, the files that stored in HDFS there content is a JSON format, for example:
{
"name":"Name",
"type":"string"
},
{
"name":"Version",
"type":"string"
},
{
"name":"r_service",
"type":"string"
},
{
"name":"r_timestamp",
"type":"long"
},
我创建了下面的函数来调用上面的两个函数(一个返回文件列表,第二个打开路径):
I created the below function to call both function above (one return list of files and the second open a path):
如何修改函数以读取文件内容并将每个文件内容添加到JSON数组并返回JSON数组?谢谢
How can I modify my function to read the files content and to add each file content to the JSON array and return an array of JSON ? Thanks
推荐答案
根据您的评论答案,您正在寻找一种方法来将文件的json内容解析为javax.json- JsonArray
.
As by your comment answer, you are looking for a way to parse the json content of the files into a javax.json-JsonArray
.
答案是 JsonReader
类.根据文档:
JsonReaderFactory factory = Json.createReaderFactory(...);
JsonReader reader = factory.createReader(...);
JsonStructure content = Jsonreader.read();
然后,该JsonStructure可以是JsonArray(检查类后,您可以将其转换为它).
That JsonStructure could then be a JsonArray (and you may cast to it, after checking the class).
它可能像这样工作(尽管我无法测试):
It might work like this (though I can't test it):
public JSONArray getSchema()
{
String avroSchemaHDFSDir = "hdfs://hadoopcluster/schemas";
try(HdfsClient hdfsClient = new HdfsClient(nameNodeHosts, hadoopZks))
{
for(int i = 0; i < hdfsClient.listeFilesHdfs(avroSchemaHDFSDir).size(); i++)
{
String fileContent = hdfsClient.listeFilesHdfs(avroSchemaHDFSDir).get(i).toString();
hdfsClient.openHdfsPath(file);
JsonReaderFactory factory = Json.createReaderFactory(...);
JsonReader reader = factory.createReader(...);
JsonStructure content = Jsonreader.read();
if (content instanceof JsonArray) {
return (JsonArray) content;
}
}
}
catch(Exception e)
{
logger.debug("get the specified schema ", e.getMessage());
}
return null;
}
这篇关于如何在Java中创建JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!