Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I GSON deserialize a variable name which includes a hyphen in Java?

Tags:

java

I am using GSON in my app. I have the following JSON response:

{
  "success":true,
  "person-name": "John"
}

So, I am creating a class like this:

class Person {
    boolean success;
    String person-name;
}

However, I am unable to create a variable person-name. How can I solve this?

like image 830
Raja Jawahar Avatar asked Feb 14 '16 11:02

Raja Jawahar


People also ask

Can you use a hyphen in variable name Java?

Having a dash in a variable, method or reference type in Java is not recommended.

Can a Java program have two different variables with the same name?

"Of course you cannot have int x and long x fields in the same class, just as you cannot have two methods with the same name and parameter list.". A better analogy is that you cannot have a method with the same name and a different type in the same class.

Can method and variable have same name?

Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur.


2 Answers

Choose a valid Java identifier and use the @SerializedName annotation to tell GSON the name of the corresponding JSON property:

import com.google.gson.annotations.SerializedName;

class Person {
    boolean success;
    @SerializedName("person-name")
    String personName;
}
like image 98
wero Avatar answered Oct 20 '22 23:10

wero


Just thought of sharing, if you are using Jackson, which I believe many people are, you can use:

import com.fasterxml.jackson.annotation.JsonProperty;

class Person {
    boolean success;
    @JsonProperty("person-name")
    String personName;
}
like image 6
Radioactive Avatar answered Oct 20 '22 23:10

Radioactive