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.

Enum constant does not exist

See original GitHub issue
This isn't a bug per say, more of a starting point for a conversation. Our
organization uses GSON to pass data between two internal applications, both
running in Java. Both applications depend on a particular in-house library,
but the receiving end isn't guaranteed to have the same version as the
sending end. This has caused some problems with our use of enums, when the
sender has knowledge of enum constants that the receiver does not know
about. It might be nice to have a way to optionally silently ignore these
mis-matches on the receiver. We have a solution that works for us, and are
somewhat curious if this is an issue for anyone else out there.


What steps will reproduce the problem?
1. Serialize an object that has an enum property to JSON
2. Deserialize the JSON in another application that does not have that enum
constant available


What is the expected output? What do you see instead?

That is the big question. In our particular instance, we would just want
that enum to be ignored. If the class that has the enum looked like

public class Something {
MyEnum a;
}

And MyEnum had "A" and "B", if the JSON said it should be "C", I would want
the property "a" to be null.

In another instance in our application, we have a class:

public class SomethingElse {
Set<MyEnum> flags;
}

If a constant of "C" were coming through in JSON, I would expect this set
to be empty, if the application containing it only knew about A and B.

What version of the product are you using? On what operating system?
Any

Please provide any additional information below.

We have overcome the first example by making our own type adapter, based on
the built-in one, that looks like:

public class EnumSafeChangeTypeAdapter<T extends Enum<T>> implements
JsonSerializer<T>, JsonDeserializer<T> {
    public JsonElement serialize(T src, Type typeOfSrc,
JsonSerializationContext context) {
        return new JsonPrimitive(src.name());
    }

    // The NULL here needs to be coupled with an instancecreator that returns
    // null as well. See VzLite for an example of this
    @SuppressWarnings("cast")
    public T deserialize(JsonElement json, Type classOfT,
JsonDeserializationContext context) throws JsonParseException {
        try {
            return (T) Enum.valueOf((Class<T>) classOfT, json.getAsString());
        }
        catch (Exception e) {
            return null;
        }
    }

    @Override
    public String toString() {
        return EnumSafeChangeTypeAdapter.class.getSimpleName();
    }
}

Also, we have to register an instance creator to handle the null, otherwise
we get other exceptions:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Enum.class, new InstanceCreator<Enum<?>>() {
public Enum<?> createInstance(Type type) {
return null;
}
});

Original issue reported on code.google.com by danw...@gmail.com on 12 Oct 2009 at 8:29

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
eranyarkoncommented, Dec 27, 2019
Glad to know that you could register a custom type adapter to address your 
use-case. 
We wouldn't like to change the design of Gson to silently ignore invalid Enum 
values 
as it may mask real bugs. Some organization prefer the fail-fast approach to 
detect 
bugs.

Original comment by inder123 on 15 Oct 2009 at 4:10

Ironically, this behavior changed all the way back in 2011 (this original issue was opened in 2009!), and since then invalid enum constant values ARE being silently ignored!

This is the PR that changed that behavior: https://github.com/google/gson/commit/214234e2029919dd7d25c4a90e2fac825795c022#diff-59aaf1be173468019fecc281a6b1890f

Specifically the change from: return Enum.valueOf(classOfT, in.nextString()); (which throws an exception if the value does not match a constant) to: return nameToConstant.get(in.nextString()); (which returns null in the same case!)

Wouldn’t it make sense to throw an exception after all, as you mentioned in your comment in 2009 (posted by “GoogleCodeExporter” in 2015… I was a bit confused by that), “We wouldn’t like to change the design of Gson to silently ignore invalid Enum values”?

0reactions
GoogleCodeExportercommented, Mar 19, 2015
I do not consider this a Gson issue, but rather a versioning issue between the 
client and server.

Original comment by joel.leitch@gmail.com on 22 Mar 2011 at 10:15

  • Changed state: Invalid
Read more comments on GitHub >

github_iconTop Results From Across the Web

No enum const class even though iterating through values ...
Enum.valueOf() only checks the constant name, so you need to pass it "COLUMN_HEADINGS" instead of "columnHeadings". Your name property has ...
Read more >
EnumConstantNotPresentExcept...
Thrown when an application tries to access an enum constant by name and the enum type contains no constant with the specified name....
Read more >
Check if an Enum Value Exists in Java - Baeldung
The name of the enum value is constant. So for instance, the name of Direction.EAST is EAST. Now we can search the direction...
Read more >
Java Enum Tutorial: 10 Examples of Enum in Java
Enum constants are implicitly static and final and you can not change their value once created. Enum in Java provides type-safety and can...
Read more >
enum in Java - GeeksforGeeks
It is not necessary that the set of constants in an enum type stay ... returns the enum constant of the specified string...
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