Created
November 8, 2012 09:26
-
-
Save jesperronn/4037744 to your computer and use it in GitHub Desktop.
(java) Mapping utitlity to up/downcast or map to objects with similar fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package utils; | |
import com.google.gson.Gson; | |
public class MappingUtil { | |
static Gson gson = new Gson(); | |
/** | |
* Object down/up casting via json | |
* | |
* Will map all similar fields from one object to another | |
* | |
* | |
* Example: | |
* BookingInput b = new BookingInput() //or load this in via a controller action param so that user fills in data | |
* | |
* //now we want to enrich the object with the relevant data which users must not tamper | |
* Booking booking = MappingUtil.map(b, Booking.class); | |
* booking.bookingNumber = bookingNumber; | |
* booking.bookingCreatedAt = at; | |
* | |
* The price penalty measured for BookingInput => Booking: 3444ms for 10,000 objects | |
* @param input the input object to map from | |
* @param outputClass which class to map into. | |
* | |
*/ | |
public static <T> T map(Object input, Class<T> outputClass) { | |
String json = gson.toJson(input); | |
return gson.fromJson(json, outputClass); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment