-1

I'm new to json and objectMapper in Java, and I have a class with two fields, and I want to create json of this class, but I only get using the mapper the attributes. How can I do this?

public class Car{
   String a;
   String b;

}

ObjectMapper mapper;
String car = mapper.writeValueAsString(new Car(a, b));

the json:

"{a: a, b: b}"

what I want: {Car: { a: a, b: b } }

  • Note that libraries like Jackson support something like this. Why exactly do you want the class in the json? What should happen if you'd have 2 or more cars? Should it be `[{"Car":{...}},{"Car":{...}}, ...]`? – Thomas Mar 25 '19 at 11:01
  • @Thomas you are right. [Here is a common SO question](https://stackoverflow.com/questions/2435527/use-class-name-as-root-key-for-json-jackson-serialization). – dbl Mar 25 '19 at 11:02

1 Answers1

2

By using JACKSON, you can achieve this by using JsonRootName annotation.

You can add it above your class with the value you want it to be your JSON root element. In your case, you should do the following:

@JsonRootName(value = "car")
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT ,use = JsonTypeInfo.Id.NAME)
public class Car{
...
} 

As you can see, we also added the JsonTypeInfo annotation which is necessary because it indicate which type of wrapping should be used.

Also you can get rid of @JsonRootName(value = "Car") and only use @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT ,use = JsonTypeInfo.Id.NAME) if you want the root field to have the same value as the class name.

Atef
  • 1,294
  • 1
  • 14
  • 27