Steven T Steven T - 3 months ago 34
JSON Question

JSON file too short to create a JsonReader

I'm using the javax.json library and am trying to read a JsonObject in a text file. I'm using this method to read a file and return it as a JsonObject:

public static JsonObject readFile(String path)
{
InputStream is = new FileInputStream(path);
JsonReader rdr = Json.createReader(is);
JsonObject obj = rdr.readObject();
rdr.close();
return obj;
}


However, when I try to read a file, I get an error at the
JsonReader rdr = Json.createReader(is)
line stating that it


"Cannot auto-detect encoding, not enough chars".


Is there anything I can do to fix this error without changing what's in the file?

The files are like this:

{"6111":1,"6121":1,"6131":1,"6141":1,"6151":1,"6162":1,"6312":1,"6323":1,"6331":1,"6343":1,"totalGames":1}

Answer

As stated the method createReader() needs more characters to detect file charset

while your file is too small to allow that, you can pass the charset to the method

try this:

public static JsonObject readFile(String path)
{
    InputStream is = new FileInputStream(path);
    JsonReader rdr = Json.createParserFactory(null).createReader(is, java.nio.charset.StandardCharsets.UTF_8);
    JsonObject obj = rdr.readObject();
    rdr.close();
    return obj;
}

if you are using different charset than "UTF8" change that for the used one

Comments