question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Support handlers for unknown properties, useful for error handling

See original GitHub issue
What steps will reproduce the problem?
1. create a JSON string containing extra attributes
2. invoke Gson.fromJson supplying a class with fewer elements
3. GSON successfully instantiates the class without protesting about the 
existence of extra attributes in the string.

What is the expected output? What do you see instead?
1. define class A containing two fields: name and surname
2. define class B containing only one field: name
3. transform an instance of class A to Json string and use the Json string 
to create an instance of class B.

GSON doesn't complain. Even if this is the intended behavior, shouldn't 
there be an option to enforce stricter parsing?

What version of the product are you using? On what operating system?
gson-1.4

Please provide any additional information below.


Original issue reported on code.google.com by mperdik...@gmail.com on 22 Jan 2010 at 10:13

Attachments:

Issue Analytics

  • State:open
  • Created 9 years ago
  • Reactions:9
  • Comments:33 (1 by maintainers)

github_iconTop GitHub Comments

16reactions
ikus060commented, Feb 27, 2017

I manage to workaround this issue using a class similar to the following:

public class ValidatorAdapterFactory implements TypeAdapterFactory {

    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        // If the type adapter is a reflective type adapter, we want to modify the implementation using reflection. The
        // trick is to replace the Map object used to lookup the property name. Instead of returning null if the
        // property is not found, we throw a Json exception to terminate the deserialization.
        TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

        // Check if the type adapter is a reflective, cause this solution only work for reflection.
        if (delegate instanceof ReflectiveTypeAdapterFactory.Adapter) {

            try {
                // Get reference to the existing boundFields.
                Field f = delegate.getClass().getDeclaredField("boundFields");
                f.setAccessible(true);
                Map boundFields = (Map) f.get(delegate);

                // Then replace it with our implementation throwing exception if the value is null.
                boundFields = new LinkedHashMap(boundFields) {

                    @Override
                    public Object get(Object key) {

                        Object value = super.get(key);
                        if (value == null) {
                            throw new JsonParseException("invalid property name: " + key);
                        }
                        return value;

                    }

                };
                // Finally, push our custom map back using reflection.
                f.set(delegate, boundFields);

            } catch (Exception e) {
                // Should never happen if the implementation doesn't change.
                throw new IllegalStateException(e);
            }

        }
        return delegate;
    }

}
11reactions
hardiksoni13commented, May 30, 2018

Do we have this fix as part of the GSON library now ?

Read more comments on GitHub >

github_iconTop Results From Across the Web

failing on unknown properties w/notification - Stack Overflow
The DeserializationProblemHandler class seems to do what you want. It allows you to implement this method to handle unknown properties:
Read more >
Best Practices for Node.js Error-handling - Toptal
This article will introduce you to error-handling in Node.js and demonstrate some of the best ... A good example is to try to...
Read more >
Error handling - Apollo GraphQL Docs
To help with debugging, Apollo Server provides an ApolloServerErrorCode enum, which you can use to check if your error is one of the...
Read more >
Complete Guide to Exception Handling in Spring Boot
A catch-all handler method is also be a good place to log exceptions as they might give insight into a possible bug. We...
Read more >
A Guide to Error Handling in Express.js | Scout APM Blog
Handling Custom Errors. Express's default error-handling middleware is super helpful for beginners to take care of unexpected, unhandled errors.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found