3

我需要像下面那样创建 json 对象。如果您注意到 applicationFiles 是 json 数组并且我已经编写了相同的代码,但 spkConf 包含嵌套的 json 对象。

JsonObjectBuilder outer = Json.createObjectBuilder(); String returnString = "";
    File file = new File(fileName);
    try (Scanner scanner = new Scanner(file);) {
        JsonObjectBuilder jsonObject = Json.createObjectBuilder();
        while(scanner.hasNextLine()){
            String line = scanner.nextLine();
            if(line !=null && line.trim().startsWith("spark.")){
                String param = line.trim();
                String [] params = param.split("=");
                if(params.length == 2){
                    jsonObject.add(params[0], params[1]);
                }

            }
        }
        returnString = jsonObject.build().toString();
    }catch(IOException e){
        e.printStackTrace();
    }outer.add("spkConfig", returnString)

给出以下输出

{"job": {
"applicationFiles": [
  "hdfs:///user/test.properties",
  "hdfs:///user/test1.json"
],
 spkConf": "{
  \"spk.home\":\"/usr/hdp/current/spk-client\",
  \"spk.master.url\":\"yarn-cluster\"
}}}

虽然我需要

{"job": {
"applicationFiles": [
  "hdfs:///user/test.properties",
  "hdfs:///user/test1.json"
],
 spkConf": {
  "spk.home":"/usr/hdp/current/spk-client",
  "spk.master.url":"yarn-cluster"
}}}

注意在 spkConfig 花括号之前没有双引号和斜线。有人可以帮忙吗?

4

1 回答 1

0

您不应将 json 结构添加为字符串 (returnString)。请试试:

JsonObjectBuilder outer = Json.createObjectBuilder();
JsonObjectBuilder jsonObject = Json.createObjectBuilder();
File file = new File(fileName);
try (Scanner scanner = new Scanner(file);) {
    while(scanner.hasNextLine()){
        String line = scanner.nextLine();
        if(line !=null && line.trim().startsWith("spark.")){
            String param = line.trim();
            String [] params = param.split("=");
            if(params.length == 2){
                jsonObject.add(params[0], params[1]);
            }

        }
    }
}catch(IOException e){
    e.printStackTrace();
}
outer.add("spkConfig", jsonObject.build());
于 2017-01-22T12:37:01.800 回答