My Controller returns a list of MyObj objects (using #ResponseBody)
public MyObj
{
int a;
int b;
}
The return JSON looks like this:
[{"a":1,"b":2},{"a":2,"b":2}]
I would like to wrap this JSON so it will return something like:
{ "data": [{"a":1,"b":2},{"a":2,"b":2}]}
From what i read i need to enable SerializationConfig.Feature.WRAP_ROOT_VALUE or (?) use
#JsonRootName("data") on top of my controller.
Also tried the #XmlRootElement, nothing seems to work.
Any idea what is the right way to wrap the list of objects with a root name?
It sounds like you're talking about putting #JsonRootName on the list rather than the object, which won't accomplish what you're trying to do.
If you would like to use #JsonRootName you'll want to enable SerializationFeature.WRAP_ROOT_VALUE like you mentioned above and add the annotation to the class:
#JsonRootName("data")
public MyObj {
int a;
int b;
}
This will wrap the objects themselves, not the list:
{
"listName": [
{
"data": {"a":1, "b":2}
},
{
"data": {"a":2, "b":2}
}
]
}
If you want to wrap the list in an object, perhaps creating a generic object wrapper is the best solution. This can be accomplished with a class like this:
public final class JsonObjectWrapper {
private JsonObjectWrapper() {}
public static <E> Map<String, E> withLabel(String label, E wrappedObject) {
return Collections.singletonMap(label, wrappedObject);
}
}
Then before you send your list back with the response, just wrap it in JsonObjectWrapper.withLabel("data", list) and Jackson takes care of the rest.
This should do the job:
List<MyObj> myList;
ObjectWriter ow = mapper.writer()
.with(SerializationFeature.WRAP_ROOT_VALUE)
.withRootName("data");
System.out.println(ow.writeValueAsString(myList));
Related
Because it's a bad habit to leave raw types like List<String> on their own in the application I decided to encapsulate it using the following class:
public class EncapsulatedList {
#JsonProperty
private List<String> someWords;
/*
Some setters, getters and so on
*/
}
But it's serialized to:
{
"someWords": [
"cheese",
"random cheese",
"more random cheese"
]
}
It would be a lot nicer to have it as a plain list like:
[
"cheese",
"random cheese",
"more random cheese"
]
Is there a clean way to achieve this using Jackson 2 without having to do this explicitly like deserializing the list first and putting it into the encapsulating class?
From the JavaDoc of #JsonUnwrapped:
Also note that annotation only applies if
Value is serialized as JSON Object (can not unwrap JSON arrays using this mechanism)
If you don't want to use a String[] or List<String> directly then you can always deserialize the type yourself, like:
class EncapsulatedListDeserializer extends StdDeserializer<EncapsulatedList> {
// ctor omitted
public EncapsulatedList deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = p.getCodec().readTree(p);
List<String> list = new ArrayList<>();
if (node.isArray()) {
for (JsonNode value : node) {
list.add(value.asText());
}
}
return new EncapsulatedList(list);
}
}
At least that somewhat abstracts the deserialization and calling the setter manually.
I have a json object like this:
{
products:[
{
name:Prod1,
quantity:3
},
{
name:Prod2,
quantity:1
}
]
}
I have my gson object like so:
public class Product{
#SerializedName("name")
public String name;
#SerializedName("quantity")
public int quantity;
}
When I set up my retrofit with something like this
#GET("/products")
void getProducts(Callback<ArrayList<Product>> c);
It will fail, obviously, because that array isn't the root object. Is there a simple way to force this to dig down into the json one level before parsing that ArrayList, or am I going to have to create a whole GSON adapter to accomplish this?
I accomplished this by creating and using my own custom deserializer. The code is simpler than a full Gson Adapter, but accomplishes what I need.
https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonDeserializer.html
Id like to represent a Class object as JSON. For example, if I have the class defintions as follows:
public class MyClass {
String myName;
int myAge;
MyOtherClass other;
}
public class MyOtherClass {
double myDouble;
}
I'd like to get the following nested JSON from a Class object of type MyClass:
{
myName: String,
myAge: int,
other: {
myDouble: double;
}
}
EDIT:
I don't want to serialize instances of these classes, I understand how to do that with GSON. I want to serialize the structure of the class itself, so that given a proprietary class Object I can generate JSON that breaks down the fields of the class recursively into standard objects like String, Double, etc.
With Jettison, you can roll your own mappings from Java to JSON. So in this case, you could get the Class object of the class you want, then map the Java returned by the getFields, getConstructors, getMethods etc. methods to JSON using Jettison.
I would recommend to use Jackson.
You can also take a look at the JSonObjectSerializer class based on Jackson which can be found at oVirt under engine/backend/manager/module/utils (you can git clone the code) and see how we used Jackson there.
Looking to do the same thing, in the end I wound up writing my own method, this does not handle all cases e.g. if one of the declared fields is a Map this will break, but this seems to be alright for most common objects:
#Override
public Map reflectModelAsMap(Class classType) {
List<Class> mappedTracker = new LinkedList<Class>();
return reflectModelAsMap(classType, mappedTracker);
}
private Map reflectModelAsMap(Class classType, List mappedTracker) {
Map<String, Object> mapModel = new LinkedHashMap<String, Object>();
mappedTracker.add(classType);
Field[] fields = classType.getDeclaredFields();
for (Field field : fields) {
if (mappedTracker.contains(field.getType()))
continue;
if (BeanUtils.isSimpleValueType(field.getType())) {
mapModel.put(field.getName(), field.getType().toString());
} else if (Collection.class.isAssignableFrom(field.getType())) {
Class actualType = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
mapModel.put("Collection", reflectModelAsMap(actualType, mappedTracker));
} else {
mapModel.put(field.getName(), reflectModelAsMap(field.getType(), mappedTracker));
}
}
return mapModel;
}
The mapped tracker there because of how I handle relationships in Hibernate; without it there is an endlessly recursive relationship between parent and child e.g. child.getFather().getFirstChild().getFather().getFirstChild().getFather()...
Using Jersey I'm defining a service like:
#Path("/studentIds")
public void writeList(JsonArray<Long> studentIds){
//iterate over studentIds and save them
}
Where JsonArray is:
public class JsonArray<T> extends ArrayList<T> {
public JsonArray(String v) throws IOException {
ObjectMapper objectMapper = new ObjectMapper(new MappingJsonFactory());
TypeReference<ArrayList<T>> typeRef = new TypeReference<ArrayList<T>>() {};
ArrayList<T> list = objectMapper.readValue(v, typeRef);
for (T x : list) {
this.add((T) x);
}
}
}
This works just fine, but when I do something more complicated:
#Path("/studentIds")
public void writeList(JsonArray<TypeIdentifier> studentIds){
//iterate over studentIds and save them by type
}
Where the Bean is a simple POJO such as
public class TypeIdentifier {
private String type;
private Long id;
//getters/setters
}
The whole thing breaks horribly. It converts everything to LinkedHashMap instead of the actual object. I can get it to work if I manually create a class like:
public class JsonArrayTypeIdentifier extends ArrayList<TypeIdentifier> {
public JsonArrayTypeIdentifier(String v) throws IOException {
ObjectMapper objectMapper = new ObjectMapper(new MappingJsonFactory());
TypeReference<ArrayList<TypeIdentifier>> typeRef = new TypeReference<ArrayList<TypeIdentifier>>(){};
ArrayList<TypeIdentifier> list = objectMapper.readValue(v, typeRef);
for(TypeIdentifier x : list){
this.add((TypeIdentifier) x);
}
}
}
But I'm trying to keep this nice and generic without adding extra classes all over. Any leads on why this is happening with the generic version only?
First of all, it works with Longs because that is sort of native type, and as such default binding for JSON integral numbers.
But as to why generic type information is not properly passed: this is most likely due to problems with the way JAX-RS API passes type to MessageBodyReaders and MessageBodyWriters -- passing java.lang.reflect.Type is not (unfortunately!) enough to pass actual generic declarations (for more info on this, read this blog entry).
One easy work-around is to create helper types like:
class MyTypeIdentifierArray extends JsonArray<TypeIdentifier> { }
and use that type -- things will "just work", since super-type generic information is always retained.
I request a rest service where the json result holds a list of place objects o just one place object but both with the same key:
{
place:[{lat:12, lon:12}, {lat:12, lon:12}]
}
or
{
place: {lat: 12, lon:12}
}
Is there a way to handle this with the jackson json parser to I've got always a list of objects?
Sure. Have you tried it? For first example, it would seem like your object model would be something like:
public class Places {
public List<Place> place:
}
public class Place {
public int lat, lon;
}
and you would get expected JSON.