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; | |
} | |
} |
What's the point in the GSON libraries here? It doesn't look like you use them.
Of course he does. JsonElement, JsonObject and JsonParser are all GSON classes.
Since JsonParser
is deprecated, What's the new way of doing this?
@pramodya1994 Simply use JsonParser.parseReader()
or JsonParser.parseString()
instead
JsonElement jsonElement = JsonParser.parseReader(new FileReader(file));
JsonObject jsonObject = jsonElement.getAsJsonObject();
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
lol