Well, I think that it does what is should do... Can somebody give me a little hint what's wrong with it?
package com.codegym.task.task33.task3304;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
/*
Using JSON to convert from one class to another
*/
public class Solution {
public static void main(String[] args) throws IOException {
Second s = (Second) convertOneToAnother(new First(), Second.class);
//System.out.println(s.getClass().getSimpleName());
First f = (First) convertOneToAnother(new Second(), First.class);
//System.out.println(f.getClass().getSimpleName());
}
public static Object convertOneToAnother(Object one, Class resultClassObject) throws IOException {
ObjectMapper mapperRead = new ObjectMapper();
StringWriter writer = new StringWriter();
mapperRead.writeValue(writer, one);
String input = writer.toString();
input = input.replace(one.getClass().getSimpleName().toLowerCase(), resultClassObject.getSimpleName().toLowerCase());
StringReader reader = new StringReader(input);
return mapperRead.readValue(reader, resultClassObject);
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "className")
@JsonSubTypes(@JsonSubTypes.Type(value = First.class, name = "first"))
public static class First {
public int i;
public String name;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "className")
@JsonSubTypes(@JsonSubTypes.Type(value = Second.class, name = "second"))
public static class Second {
public int i;
public String name;
}
}