JSON fields name for POJO class

1162 views java
-1

I have a simple Java class:

class Feed { 
private String fieldOne;
private String fieldTwo;
}

and a JSON connected with this class:

{
  "feed": {
    "field_one": "1.780",
    "field_two": "1.810"
}

but when I send this json to server, all class fields are null. If i change fields name in JSON to fieldOne and fieldTwo it works fine. But is it possible to read this json without doing any changes in fields name in JSON or class?

answered question

Depending on your underlying JSON provider, you should be able to annotate your class to say what the expected field names are.

So I need to use @JsonProperty annotation and this is a solution?

In addition to rmlan's comment: some libraries such as Jackson support the use of mixins, i.e. you don't have to change the Feed pojo to "add" the annotations (if you really need to keep Feed as it is). Others make use of some sort of configuration, e.g. via some file.

1 Answer

5

You should do this :

class Feed { 
@XmlElement(name="field_one")
private String fieldOne;

@XmlElement(name="field_two")
private String fieldTwo;
}

posted this

Have an answer?

JD

Please login first before posting an answer.