Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshalling two similar json fields to the same java field

Tags:

java

json

jackson

I have a sample dummy JSON response that looks like :

    {
        "id": 1,
        "teacher_name": "Foo",
        "teacher_address": "123 Main St.",
        "teacher_phone_num": 1234567891,
        "student_name": "Bar",
        "student_address": "546 Main St.",
        "student_phone_num": 9184248576
    }

The above is a silly example, but it helps illustrate the issue I am having trying to de-serialize the above into a Java class called "Employee" using Jackson:

public class Employee {
    String name;
    String address;
    String phoneNumber;
}

The issue is that the JSON has two different prepends so I cannot annotate each field in Employee and have the object mapper map teacher_name and student_name to the name field in an Employee object. Is there a way in Jackson to specify two differently named nodes to map to the same Java field?

like image 639
John Baum Avatar asked Oct 18 '22 12:10

John Baum


1 Answers

So in my example, I should end up with two Employee objects (I am guaranteed to have one pair per response)

It is not possible with Jackson. It is designed to map one-to-one: one json object to one java object. But you want to end up with two java objects from one json.

I would recommend you to go with strait forward way by implementing some processing level that will consume Response and map it to two Employee objects.

like image 95
Sasha Shpota Avatar answered Oct 21 '22 09:10

Sasha Shpota