-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Open
Description
I written a JsonUtils jar in Java and add it as dependency to Grails application.
I want to convert a json file to object so I wrote this method in JsonUtils class.
public static <T> T fromJSON(Reader reader, Class<T> theClass) throws IOException {
// gson is sensitive to white spaces. 1 option is to use gson's JsonReader.setLinient(true).
// but that will allow malformed json. So, the hack is to read the contents and trim the lines
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(reader);
for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
sb.append(line.trim());
}
bufferedReader.close();
return JSONUtils.fromJSON(sb.toString(), theClass);
}
public static <T> T fromJSON(String json, Class<T> theClass) {
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
return gson.fromJson(jsonObject.get(theClass.getName()), theClass);
}I wrote a test in java and it was passing correctly converting json file to required object.
Now I use this code in Grails application but when I try to get object it returns null always
DSDescriptor descriptor = JSONUtils.fromJSON(new FileReader(newPath.toFile()), new TypeToken<DSDescriptor>(){}.getType())
descriptor
However when I use Gson's public <T> T fromJson(Reader json, Class<T> classOfT) throws JsonSyntaxException, JsonIOException method directly in grails application, it parse it correctly.
DSDescriptor descriptor = new Gson().fromJson(new FileReader(newPath.toFile()), DSDescriptor.class)
Metadata
Metadata
Assignees
Labels
No labels