Reputation: 2785
I am interfacing to a library. I get List<List> foodItemsList
How do I serialize foodItemsList
using Jackson? This is happening while handling a GET.
I have understood how to serialize an object using Jackson/Restlet, but I am unable to figure it out for a list.
For a single object here is what I do
@Get("json")
public Representation represent(Variant variant) throws ResourceException {
:
ObjectMapper mapper = new ObjectMapper();
String myFinString = mapper.writeValueAsString(profileSupportedInfo);
:
return myFinstring
}
getter setter for member data in profileSupportedInfo is what I provide.
Before creating mapper object, here is the call I make
List<List> totalfoodItem = someMemberFunc();
ObjectMapper mapper = new ObjectMapper
// my question - how do I serialize totalFoodItem
The preferred representation of totalFoodItem
in JSON is as given below
{
"food":[
{"name":"apple","img_loc":"123_apple.jpg","energ":210,"food_unit":"1"},
{"name":"rice","img_loc":"134_rice.jpg","energ":123,"food_unit":"100 gm"},
:
]
}
What am I missing / failing to understand? Thank you
Upvotes: 0
Views: 942
Reputation: 611
I'm afraid in order to successfully serialize a List you have to turn it into an array. The JVM won't serialize Lists with the appropriate type information (you'll just get a list of generic Objects when you deserialize), and this is not Jackson's fault. However, if you serialize an array, the array must be typed and the objects inside the array will retain their types as well.
From your desired JSON, it appears all you need is a helper class that can collect the food information such as the following:
public class Food {
private String name;
private String img_loc;
private String energ;
private String food_unit;
public FoodItem(String name, String value, String energ, String food_unit) {
this.name = name;
this.value = values;
this.energ = energ;
this.food_unit = food_unit;
}
}
Now all you need is an object that has an array of Food objects as an attribute:
public class TotalFoodItem {
private Food[] food;
...
}
and you can serialize that object. Jackson probably won't produce JSON that looks exactly like your desired JSON (I haven't tried this code myself) but it should be pretty close.
Upvotes: 1