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;
}
}
@ploderup
Copy link

What's the point in the GSON libraries here? It doesn't look like you use them.

@Wunst
Copy link

Wunst commented Apr 11, 2021

Of course he does. JsonElement, JsonObject and JsonParser are all GSON classes.

@pramodya1994
Copy link

Since JsonParser is deprecated, What's the new way of doing this?

@Lulonaut
Copy link

@pramodya1994 Simply use JsonParser.parseReader() or JsonParser.parseString() instead

@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