Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map java object attribute(my_name) with json attribute (my-name)?

Tags:

json

jackson

I am using jackson json api to map json data to java objects. All is well in case of same object attribute names with json attributes. Now i have a situation where i am getting json data attribute with -. (my-name).

In java we can't include - in variable names.

import org.codehaus.jackson.map.ObjectMapper;

private static final ObjectMapper mapper = new ObjectMapper();

User user = mapper.readValue("{my-name:\"abcd\"}", User.class);

public class User {private String my_name; /*get-set methods*/}

Is there anything i need to apply in User.class.

I don't want to change my code so much.

like image 483
Satish Pandey Avatar asked Aug 21 '12 06:08

Satish Pandey


People also ask

How do you pass a JSON object into a Map?

The first way to convert JSON to Map in Java is by using Jackson. In Jackson, there is a method available with the name readValue(json, Map. class) and we can call this method by using the ObjectMapper object. This method takes JSON as input.

How do you Map a JSON array to a list of Java objects?

This is done via the readValue() method, by specifying the JSON contents (String or file) and by specifying the POJO we'd like to map to.


1 Answers

In your java class you can give any name as you like

Ex. private String myName;

But in the setter method just write:

@JsonProperty("my-name")
public void setMyName(String myName) {
    this.myName = myName;
}
like image 80
Ajit Avatar answered Sep 27 '22 16:09

Ajit