Search code examples
javajsonyamljackson-databindsnakeyaml

Convert JSONObject to Yaml in JAVA 8


i am using jackson-dataformat-yaml-2.7.6 jar which is old version and cannot upgrade

trying to convert JSONObject to yaml

so below is my code

    private static String processFilesForYml(JSONObject a_Obj) throws Exception
    {
         
        ObjectMapper objectMapper = new ObjectMapper();
       
        // Read file as JsonNode
        JsonNode jsonNode = objectMapper.readTree(a_Obj.toString());
        // Convert it into YAML String
        return new YAMLMapper().writeValueAsString(jsonNode); 
                     
    }

i am getting output like this

---
nlu:
- lookup: "Project"
  examples:
  - "hybrid"
  - "hybrid test"
  - "hybrid#!1"
  - "hyb_2"

and out expected is | pipe after example:

---
nlu:
- lookup: "Project"
  examples: | //pipe here
  - "hybrid"
  - "hybrid test"
  - "hybrid#!1"
  - "hyb_2"

is there any other way do this cannot use new jar

below is my input JSONObject

{
  "nlu": [
    {
      "lookup": "Project",
      "examples": [
        "hybrid",
        "hybrid test",
        "basic work management",
        "basictemplateprj",
        "seo a/b testing",
        "seotemplateprj",
        "marketing strategy",
        "marketingtemplateprj",
        "hybrid#!4"
      ]
    }
  ]
}

Solution

  • If it were JSON what is the desire object?

    A:

    {
      "nlu": [
        {
          "examples": "- hybrid\n- \"hybrid test\"\n- \"hybrid#!1\"\n- hyb_2\n",
          "lookup": "Project"
        }
      ]
    }
    

    or B:

    {
      "nlu": [
        {
          "examples": [
            "hybrid",
            "hybrid test",
            "hybrid#!1",
            "hyb_2"
          ],
          "lookup": "Project"
        }
      ]
    }
    

    According to the desired YAML file you want the first option. This means that you are trying to serialize a list a string. I would suggest to convert your list to an object and try specifying the exact serialization