java - Serializing List<Item> to JSON with custom fields -
i'm trying create simple rest api spring mvc, returns data in json format.
i'm working on method returns list of authors, that's accessed example.com/api/authors?find=somename
i have jpa entity called authors. have @service fetches list<author> collection. author entity has properties, id, firstname, lastname, birthdate.
what i'm trying achieve json result like:
{ "data": [ { "id": 1, "name": "leo tolstoi", "age": 49 }, { "id": 2, "name": "billy shakespeare", "age": 32 } ] } as can see, result has 2 fields not directly entity, rather should generated author entity's values. name field author.getfirstname() + " " + author.getlastname() , age someutilityclass.calcage(author.getbirthdate())
i'm trying figure out how sort of output using gson.
what do, fetch data service class , iterate on it, saving each iteration row map (or something, maybe save each row list<authorjson> entity, has fields id, name, age). approach doesn't seem clean.
can guys suggest solutions?
you should use custom serializer author.
since need serializer, here example of can do. note age off 1 of time.
public static void main(string[] args) { gsonbuilder gbuild = new gsonbuilder(); gbuild.registertypeadapter(author.class, new authorserializer()); author author = new author(); calendar cal = calendar.getinstance(); cal.set(calendar.year, 1988); cal.set(calendar.month, 1); cal.set(calendar.day_of_month, 1); author.setbirthdate(cal); author.setfirstname("john"); author.setlastname("smith"); gson gson = gbuild.setprettyprinting().create(); system.out.println(gson.tojson(author)); } private static class authorserializer implements jsonserializer<author> { @override public jsonelement serialize(author src, type typeofsrc, jsonserializationcontext context) { calendar today = calendar.getinstance(); int age = today.get(calendar.year) - src.getbirthdate().get(calendar.year); string fullname = src.getfirstname() + " " + src.getlastname(); jsonobject obj = new jsonobject(); obj.addproperty("fullname", fullname); obj.addproperty("age", age); return obj; } }
Comments
Post a Comment