我正在尝试编写一个抽象类,它将使用jackson-databind的ObjectMapper将字符串值映射到对象成员变量,反之亦然。这个抽象类将由json的每个pojo扩展。
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class JsonToString {
public JsonToString toObject(String jsonString){
ObjectMapper mapper = new ObjectMapper();
try {
mapper.readValue(jsonString, this.getClass());//problem
System.out.println("inside object function of jsontostring : "+this);
} catch (JsonParseException e) {
System.out.println("Exception occured in mapping jsonString received to object" + e);
} catch (JsonMappingException e) {
System.out.println("Exception occured in mapping jsonString received to object" + e);
} catch (IOException e) {
System.out.println("Exception occured in mapping jsonString received to object" + e);
}
return this;
}
public String toString(){
ObjectMapper mapper = new ObjectMapper();
String json = new String();
try {
json = mapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
System.out.println("Trouble in mapping object to string in json class : "+this.getClass().getName());
}
return json;
}
}
这个课程将由每个json pojo扩展。
所以在这里我想返回已经完成映射的子类的对象。有人可以帮我拿到物品并将其归还。
我以这种方式调用此方法:
ITAGResponseInfo response = new ITAGResponseInfo();
response = (ITAGResponseInfo)response.toObject(cOutput);
System.out.println("Printing from the itagresponseinfo object : "+response);
此处ITAGResponseInfo扩展了JsonToString类。