3

I need to creatre json object like below. If you notice applicationFiles is json array and I have written code for the same but spkConf contains nested json objects.

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)

Gives below output

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

While I need

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

Notice no double quote and slashes before spkConfig curly braces. Can someone please help?

1 Answers1

0

You should not add your json structure as a String (returnString). Please try:

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());
Bruno
  • 141
  • 9