On Sat, Dec 29, 2018 at 3:01 PM MV <
mee...@gmail.com> wrote:
>
> Hi there,
>
> I am using Akka Actor framework to receive messages as Java objects. When I receive the message, I do the following:
> (1) Use ObjectMapper.withPrettyWriter().writeValueAsString(<java pojo>)
> (2) Open a file and use java.nio.Files API to write to the file. When I write to the file, I use Arrays.asList(json_string_from step_1) with file in append mode.
Ok, a few questions. Let's see if I can help.
>
> I am having a few issues:
> (1) I am unable to write the first json string as an array. When I write it the first time, I would like to see:
> [
> {
> "name" : "test"
> "age" : 29
> }, --> I don't get this "comma" with closing "]"
> ] ---> don't get this.
>
> All I get is :
> {
> "name" : "test"
> "age" : 29
> }
>
> (2) While calling successive Files.write (...), the output in the file is
> {
> "name" : "test"
> "age" : 29
> }
> {
> "name" : "test2"
> "age" : 30
> }
> This results in malformed JSON file and I cannot use objectMapper.readValue as a list. Looks like I have to use Files API to load the data.
>
> Qn) How do I write a single json as an array with ", ]" and then append to this list as data starts flowing in through the messaging architecture?
> I did see some solution on reading the file first, add new data to the array and then write the whole list again to the file each time. I think with messaging architecture this is not very efficient as we will see a lot of messages.
> Is there someway to open the file and write the first data and then keep appending to the file?
>
> Thanks
> MV
Ok, first things first. I think that your writing actually makes
sense, and although you can not read it with
`ObjectMapper.readValue()` (since it is a sequence of JSON values and
not a single JSON value), you can read it with something like:
----
MappingIterator<POJO> it = mapper.readerFor(POJO.class)
.readValues(file); // note it is "values" NOT "value"
while (it.hasNextValue()) {
POJO p = it.nextValue();
}
it.close();
-----
Now; if you really do want a JSON array with values, there are ways to
achieve that. You would probably want to create a `JsonGenerator`
directly (from `JsonFactory`), call `writeStartArray()`, and then for
each POJO either:
1. Unless you really have to do `writeValueAsString()` separately (if
so, why?), just use
ObjectMapper.writeValue(jsonGenerator, value)
which will handle addition of separators etc
2. If you do have to create intermediate JSON string or byte array,
instead use generator directly
jsonGenerator.writeRawValue(encodedJson)
and then at the end of output, call `jsonGenerator.writeArray()` to
get the close marker.
But as I said, first solution seems like a better choice to me given
information here.
-+ Tatu +-