1

I'm sending a file over the network which is in JSON format and wanting to retrieve information from it. The file is created using the File.createTempFile method. Here's the code:

File patchFile = File.createTempFile("indexer", ".pf", null);
try(FileOutputStream fos = new FileOutputStream(patchFile)) {
    byte[] patchFileBytes = new byte[payloadLength];
    buffer.readBytes(patchFileBytes);
    fos.write(patchFileBytes);
}

I'm trying to find the best way to read the patchFile as JSON and get values from it. The generated files structure looks like this(on the client):

{
  "0": [
    {
      "fileId": "Cache.dat",
      "fileChecksum": "d41d8cd98f00b204e9800998ecf8427e"
    },
    {
      "fileId": "Character.fbx",
      "fileChecksum": "d41d8cd98f00b204e9800998ecf8427e"
    },
    {
      "fileId": "Skybox.png",
      "fileChecksum": "d41d8cd98f00b204e9800998ecf8427e"
    }
  ],
  "1": [
    {
      "fileId": "indexer.pf",
      "fileChecksum": "f8130e38ce5c58ccbf200d24c2629632"
    }
  ]
}

Currently I've got the file being sent over and read into memory as you can see above, but I'm unsure as to where to go from here on actually reading the data, could anyone help me out?

I'm using GSON.

2 Answers 2

1

What I would suggest is to avoid writing to a temporary file, instead wrap the buffer with a reader and use in one of the API's (I'm assuming that the buffer is an InputStream, then use java.io.InputStreamReader to convert it into a Reader)

GSON has a lot of API's to perform your required task:

Examples:

To follow the iterative approach, then look at com.google.gson.JsonParser#parse it accepts reader or string to get elements.

If you know what is the type of the element being deserialized, then you can look at using com.google.gson.Gson#fromJson methods.

See the following API docs, it might be helpful:
JsonStreamParser
JsonParser
Gson

Sign up to request clarification or add additional context in comments.

Comments

1

You did not mention how big your file can be. If it is not too big then you could just use Apache Commons IO and IOUtils.toString and read the entire file content into String. And since you already know GSON it should be pretty simple from there.

2 Comments

The file can be virtually any size, depends on the amount of files indexed.
Then the approach suggested by MJSG is much better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.