Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map Json to Java classes when some variable names begin with a number?

Recently I've been playing with a webservice that returns a json object like this

{
  "id": 88319,
  "dt": 1345284000,
  "name": "Benghazi",
  "coord": {
    "lat": 32.12,
    "lon": 20.07
  },
  "main": {
    "temp": 306.15,
    "pressure": 1013,
    "humidity": 44
  },
  "wind": {
    "speed": 1,
    "deg": -7
  },
  "clouds": {
    "all": 90
  },
  "rain": {
    "3h": 3
  }
}

I have automatically generated Java classes mapping to that json data. The problem is I cannot generate a Java class with an attribute named 3h (in Java as in many other languages variable identifiers cannot begin with a number). As a hack around I have redefined the attribute 3h as h3, and whenever I receive a json response from the web service I replace the string "3h" by "h3".

However, that approach is only appropriate for small projects. I would like to know if there is a more convenient approach to deal with this kind of situation.

Notes: For this particular example I used an online tool that generated the java classes given a json example. In other situations I have used Jackson, and other frameworks. ¿Is the answer to this question framework dependent? To be more concrete, and having the future in mind, I would like to adhere to the json-schema specification

like image 702
magomar Avatar asked Oct 04 '22 13:10

magomar


2 Answers

If using Gson you can do it with @SerializedName annotation.

Java Class:

public class JsonData {

    @SerializedName("3h")
    private int h3;

    private String name;

    public JsonData(int h3, String name) {
        this.h3 = h3;
        this.name = name;
    }

}

Serialization: (same class works for fromJson() as well)

// prints: {"3h": 3,"name": "Benghazi"}
System.out.println(new Gson().toJson(new JsonData(3, "Benghazi")));

Reference:
@SerializedName Annotation

like image 200
Ravi K Thapliyal Avatar answered Oct 12 '22 12:10

Ravi K Thapliyal


Here is what you're looking for. Simple as it seems, getting the syntax right took me a while.

public class Rain {
    @JsonProperty("3h")
    public BigDecimal detail = BigDecimal.valueOf(0);
}

You may not need it, but I set the default to 0. "3h" is the name of the key. "detail" is the name I gave the property to hold the value that WAS represented by "3h".

like image 27
Forrest Avatar answered Oct 12 '22 12:10

Forrest