David
David

Reputation: 415

Spring mvc Controller binding Nested JSON to POJO with one to many relationship

I'm trying to figure out how to bind nested JSON data received from an ajax post to a POJO that has a one to many relationship with another POJO in the spring mvc framework.

for example I have 2 classes:

public class MagTemplate implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private BigInteger magTemplateId;

    private String templateName;

    //bi-directional many-to-one association to MagZone
    @OneToMany(mappedBy="magTemplate", cascade = CascadeType.PERSIST)
    private List<MagZone> magZones;

    public MagTemplate() {
    }

    //getters and setters
}

public class MagZone implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private BigInteger magZoneId;

    private String zoneName;

    //bi-directional many-to-one association to MagTemplate
    @ManyToOne
    @JoinColumn(name="magTemplateId")
    private MagTemplate magTemplate;

    public MagZone() {
    }

    //getters and setters
}

And I have a JSON object that looks like this:

{
    templateName : "template 1",
    magZones : [

            zoneName : "zone 1"
        },
        {
            zoneName : "zone 2"
        },

            zoneName : "zone 3"
        }
    ]
}

When I tried to create a controller that looked like this:

@RequestMapping(value = "/saveTemplate", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = "application/json")
@ResponseBody
public AjaxResponse saveTemplate(HttpServletRequest request, @RequestBody MagTemplate magTemplate){
    //controller code    
}

and then do an ajax post like so:

$.ajax({
    headers: { 
        'Accept': 'application/json',
        'Content-Type': 'application/json' 
    },
    contentType : "application/json",
    method: "POST",
    dataType: 'json',
    url: url,
    data: JSON.stringify(jsonData),
    success: function(response){

    },
    error:function(jqXHR, textStatus, errorThrown){
        console.error(jqXHR);
        console.error('status: ' + textStatus + "\n" + "error: " + errorThrown);
    }
 });

I get an HTTP400 error saying that its a bad request. I have the spring jackson-databind dependency and it seems to be working because I can bind a single MagZone object with another controller.

How do I get the spring controller to do a deep bind of the JSON data so that I have a single MagTemplate object with a list of the 3 MagZone objects? I know that this is possible in other mvc frameworks but I cant seem to find an example of it working in spring.

Upvotes: 2

Views: 1450

Answers (1)

Alex
Alex

Reputation: 11579

Add @JsonIgnore to the fields (or methods) which you don't use in JSON to exclude from deserialization.

Upvotes: 1

Related Questions