简体   繁体   English

Json到具有类的Java对象 <?> 成员变量

[英]Json To Java Object having Class<?> member variable

public class A {

    private Class<?> dataType;
    public Class<?> getDataType() {
        return dataType;
    }
    public void setDataType(Class<?> dataType) {
        this.dataType = dataType;
    }

}
public class B {

   public static void main(String[] args) {

       try {
            File file = new File( "fileName.json");
            A a = new ObjectMapper().readValue(file, A.class);
          } catch (IOException io) {
                io.printStackTrace();
            }
   }
}
  • Contents in fileName.json file : { "dataType" : "java.lang.String" } fileName.json文件中的内容:{“ dataType”:“ java.lang.String”}

  • I got error : org.codehaus.jackson.map.JsonMappingException: Can not access private java.lang.Class() (from class java.lang.Class; failed to set access: Can not make a java.lang.Class constructor accessible. 我收到错误消息:org.codehaus.jackson.map.JsonMappingException:无法访问私有java.lang.Class()(来自类java.lang.Class;无法设置访问权限:无法使java.lang.Class构造函数可访问。

  • Is there wrong representation of data in json file, if yes then can any one suggest me what will be correct notation of class A in json file. json文件中的数据表示是否错误,如果可以,那么任何人都可以建议我json文件中A类的正确表示法是什么。
  • I got the solution : We have to use Jackson annotation for this. 我得到了解决方案:为此,我们必须使用Jackson注释。 So rewrite class A. 因此,重写A类。

import org.codehaus.jackson.annotate.JsonCreator; 导入org.codehaus.jackson.annotate.JsonCreator;

import org.codehaus.jackson.annotate.JsonProperty; 导入org.codehaus.jackson.annotate.JsonProperty;

public class A { 公开课A {

private Class<?> dataType;
public Class<?> getDataType() {
    return dataType;
}
public void setDataType(Class<?> dataType) {
    this.dataType = dataType;
}

@JsonCreator
public A(@JsonProperty("dataType") String dataType)
{ 
    try {
        this.dataType = Class.forName(dataType);
    } catch (ClassNotFoundException c) {
        c.printStackTrace();
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM