google / google/gson

Gson not working properly in grails but Work in Java Perfectly

Open
#1,009 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
24.2k
Forks
4.5k
Avg merge
6d 4h
Merged PRs (30d)
12

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.

```java
public static T fromJSON(Reader reader, Class 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 fromJSON(String json, Class 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

```grails
DSDescriptor descriptor = JSONUtils.fromJSON(new FileReader(newPath.toFile()), new TypeToken(){}.getType())
descriptor
```

However when I use Gson's `public T fromJson(Reader json, Class classOfT) throws JsonSyntaxException, JsonIOException` method directly in grails application, it parse it correctly.

```
DSDescriptor descriptor = new Gson().fromJson(new FileReader(newPath.toFile()), DSDescriptor.class)
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.