Can I name my variable ‘public’ in Java for JSON serialization/deserialization? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Can I name my variable ‘public’ in Java for JSON serialization/deserialization? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

So I’m working with a public API that sends me a JSON object with a boolean field named ‘public’.

{  
    ...
    "public" : true,
    ...
}

I’m using GSON to parse this into a Java class, but this forces me to declare the following variable, which of course the Java lexer/parser does not agree with:

private boolean public;

Is there any way to allow my variable to be named public?

Answer

Use Gson’s @SerializedName annotation.

@SerializedName("public")
private boolean someOtherName;

You can’t use the word public (or any of the other reserved keywords) as an identifier name in Java source code.

Most feature-rich JSON parsers will have such an annotation or other mechanism for naming JSON keys, which don’t have as many naming restrictions.

We are here to answer your question about Can I name my variable ‘public’ in Java for JSON serialization/deserialization? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji