Link to home
Start Free TrialLog in
Avatar of BeginnerVB_Net
BeginnerVB_Net

asked on

jackson set serialization using object mapper

Lets say, I have below classes.

@JsonRootName(value = "car")
public class car {
private String make;
private String model;
//getters and setters
}

public class Automobile {
    private String color;
    private String type;
    private Set<Car> cars = new HashSet<>();
//getters and setters
}

When I serialize Automobile using below code
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
mapper.writeValueAsString(Automobile);

I am getting the output
{
  “Automobile”:
   {
    “color”: “red”,
    “type”: “four wheel”,
    “cars”:[{“make”:”Honda”,”model”:”cry”}]
   }
}

But I want something like below
{
  “color”: “red”,
  “type”: “four wheel”,
   “cars”: {
      “car”: [{“make”:”Honda”,”model”:”cry”}]
    }
}

How can i use jackson annotations so that i can get the output i want
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

What's the difference between Automobile and car (that should be Car in Java btw) - i thought they were synonyms?
Avatar of BeginnerVB_Net
BeginnerVB_Net

ASKER

i was just giving a sample. i couldn't come up with a better name :)
You can certainly make the output as you have stated, but I am not sure it is exactly how you would want it. So before we go too far down a wrong path, can you give us the required example output if there were more than one "Car" object in the cars Set?
For multiple cars, output should look like below
{
  “color”: “red”,
  “type”: “four wheel”,
   “cars”: {
      “car”: [{“make”:”Honda”,”model”:”crv”}, {“make”:”Toyota”,”model”:”carolla”} ]
    }
}
ASKER CERTIFIED SOLUTION
Avatar of BeginnerVB_Net
BeginnerVB_Net

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I was looking for some other solution through annotations but what i finally ended up doing seems to be the right thing to do