Created
November 16, 2011 22:01
-
-
Save madonnelly/1371597 to your computer and use it in GitHub Desktop.
Converting a file to JsonObject with GSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
commented
Jan 23, 2023
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