Skip to content

Instantly share code, notes, and snippets.

@madonnelly
Created November 16, 2011 22:01
Show Gist options
  • Save madonnelly/1371597 to your computer and use it in GitHub Desktop.
Save madonnelly/1371597 to your computer and use it in GitHub Desktop.
Converting a file to JsonObject with GSON
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class GSONFileTest {
public static void main(String[] args)
{
convertFileToJSON ("/tmp/test.json");
}
public static JsonObject convertFileToJSON (String fileName){
// Read from File to String
JsonObject jsonObject = new JsonObject();
try {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(new FileReader(fileName));
jsonObject = jsonElement.getAsJsonObject();
} catch (FileNotFoundException e) {
} catch (IOException ioe){
}
return jsonObject;
}
}
@carmuno
Copy link

carmuno commented Jan 23, 2023

    JsonElement jsonElement = JsonParser.parseReader(new FileReader(file));
    JsonObject jsonObject = jsonElement.getAsJsonObject();

@fucksophie
Copy link

Now-a-days the best method on how to do this is by

JsonParser.parseString(Files.readString(path)).getAsJsonObject()

Extremely simple.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment