79 lines
2.4 KiB
Java

package at.reisinger.server.helper;
import at.reisinger.Card;
import at.reisinger.Cards;
import at.reisinger.Package;
import at.reisinger.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Map;
/**
* Hilfsfunktionen für Jackson Json
*/
public class JsonHelper {
/**
* Wandelt ein Package in form einer ArrayList<Card> om ein Json um
* @param listCards Cards die in dem Json stehen sollen
* @param name Name des Packages
* @return Json String des Packages
*/
public static String packageListToJson(ArrayList<Card> listCards, String name){
Package packageCards = new Package(new Cards(listCards),name, 5);
return objToJson(packageCards);
}
/**
* Wandelt ein Package Objekt in ein Json um
* @param obj Objekt das in ein Json umgewandelt werden soll
* @return Json String des Packages
*/
public static String objToJson(Object obj){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper = new ObjectMapper();
String packageJson = "";
if(obj != null) {
try {
packageJson += objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
packageJson = "Error: JsonProcessingException -> " + e.getMessage();
}
return packageJson;
}else{
return null;
}
}
public static Map<String, Object> jsonPayloadToMap(String payload){
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.readValue(payload, new TypeReference<Map<String,Object>>(){});
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
public static String userToJson(User user){
//User to json
ObjectMapper objectMapper = new ObjectMapper();
objectMapper = new ObjectMapper();
String userJson = "";
if(user != null) {
try {
userJson += objectMapper.writeValueAsString(user);
} catch (JsonProcessingException e) {
userJson = "Error: JsonProcessingException -> " + e.getMessage();
}
return userJson;
}else{
return null;
}
}
}