1

I would like to parse some JSON and for that I need to create a POJO class. My POJO looks like below;

public class MyPOJO {

    private String public;

    public String getPublic(){
        return public;
    }

    public void setPublic(String public){
        this.public = public;
    }
}

There is an attribute public in the JSON, so I have to include it here. But java is showing error because public is a access modifier. How can I fix this?

Alfred
  • 21,058
  • 61
  • 167
  • 249
  • 2
    No it is not possible. You cannot use a keyword as an identifier, and the modifiers are all keywords. – Stephen C Apr 02 '20 at 06:35
  • 1
    Does this answer your question? [Reserved words as names or identifiers](https://stackoverflow.com/questions/423994/reserved-words-as-names-or-identifiers) – Frederik Hansen Apr 02 '20 at 06:36
  • @StephenC then is there any way to parse the JSON? – Alfred Apr 02 '20 at 06:36
  • 2
    If you're using something like Jackson, you can change the property name with annotations (`@JsonProperty("public") private String publicValue;`) – ernest_k Apr 02 '20 at 06:37
  • and if you want more control you can preprocess the json https://stackoverflow.com/questions/52991140/jackson-preprocess-deserialization – Jocke Apr 02 '20 at 06:38
  • Strictly speaking, the problem is not in the parsing. The problem is in the binding of the parsed JSON to a POJO. (The old "json.org" library will have no problems parsing your JSON.) – Stephen C Apr 02 '20 at 06:40

1 Answers1

0

Public is a key word in java so you can't use public as a name for an attribute or variable. (See also https://en.wikipedia.org/wiki/List_of_Java_keywords)

You have to rename the attribute inside your POJO class. For example publicAttr or something like that.

sgcode
  • 11