Search code examples
javajsonjbossapache-cameljbossfuse

How to unmarshal JSON to multiple items with JBoss Fuse (camel)?


I currently have the following simplified JSON (test.json):

{"type":"monkey","food":"banana"},{"type":"dog","food":"bone"},{"type":"cat","food":"fish"}

Doing the following:

from("file:/tmp/input").routeId("test")
                        .unmarshal().json(JsonLibrary.Jackson)
                        .log("After unmarshall:\n ${body}");

When dropping the JSON file into the input folder, I only get the following map:

{type=monkey, food=banana}

How to get all items into the mapping?


Solution

  • If you want to get all then put them to an array like

    [{"type":"monkey","food":"banana"},{"type":"dog","food":"bone"},{"type":"cat","food":"fish"}]
    

    Then setup dataFormat with useList option true. In Xml DSL that i tried is

    <dataFormats>
      <json id="json" library="Jackson"  useList="true"/>
    </dataFormats>
    

    In Java is

    JacksonDataFormat json = new JacksonDataFormat(); 
    json.useList();
    

    Then use unmarshall with the preceding data format

    XML DSL:

    <unmarshal ref="json"/>
    

    So you should have :

    from("file:/tmp/input").routeId("test")
                            .unmarshal().json(json)
                            .log("After unmarshall:\n ${body}");
    

    And the output is a list:

     [{type=monkey, food=banana}, {type=dog, food=bone}, {type=cat, food=fish}]