如何从JSON正确读取此泛型?

如何解决如何从JSON正确读取此泛型?

我对我的第一个泛型容器有一定的信心,但对如何在客户端上进行强制转换表示怀疑。这是我参与学习<T>知识之前的工作方式:

CommonNounContainer typeContainer = new Json().fromJson(CommonNounContainer.class,result);

我当时正在考虑必须为每个类创建一个不同的容器,这似乎不是一个好的设计。以下是我更新后的无法正常工作的尝试,以读取我的新泛型容器:

JSONContainer<CommonNoun> typeContainer = new Json().fromJson(JSONContainer.class,result);

我的IDE对此短语不满意,请注意:

类型安全:无需检查JSONContainer类型的表达式 转换以符合JSONContainer

执行后,我的错误日志显示为:

result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
com.badlogic.gdx.utils.SerializationException: Field not found: cid (java.lang.Object)
Serialization trace:
{}.myObject.cid
myObject (semanticWeb.rep.concept.JSONContainer)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:854)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1011)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:863)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1011)
    at com.badlogic.gdx.utils.Json.fromJson(Json.java:789)
    at com.b2tclient.net.Communicator$2.handleHttpResponse(Communicator.java:95)
    at com.badlogic.gdx.net.NetJavaImpl$2.run(NetJavaImpl.java:224)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:830)

我确定应该以某种方式在等号右边添加对CommonNoun类型的引用,但我还无法弄清楚。我该怎么做?关于泛型,转换,JSON和剥离类信息,有很多适用的文章。我尝试遵循的其中之一与上面的强制转换无关,认为在构造过程中将T类添加为容器内的私有变量:

How do I get a class instance of generic type T?

但是我遇到了类似的语法问题,试图在过程中的另一个位置正确地引用该类。我也有疑问,我可以在告诉JSON如何对文件中的信息进行分类之前从JSON文件读取此类变量。

Javadoc for the fromJson(Class<T>,String) method

Type Parameters:
   <T> 
Parameters:
   type May be null if the type is unknown.
   json 
Returns:
   May be null. 

我可能已经有一个由重复数据删除器提交的可行答案,但是根据要求,这是CommonNounContainer和JSONContainer类:

import java.util.ArrayList;

public class CommonNounContainer {

   private CommonNoun myCommonNoun;
    private ArrayList<CommonNounContainer> children;
    public CommonNounContainer(CommonNoun concept) {
        myCommonNoun = concept;
        children = new ArrayList<CommonNounContainer>();
    }

    //Creates an empty shell.  This would be for categories you want to group by,but not display/select in the select box.
    public CommonNounContainer() {
        children = new ArrayList<CommonNounContainer>();        
    }
    
    public void addChildren(ArrayList<CommonNounContainer> newChildren) {
        children.addAll(newChildren);
    }

    public void addChild(CommonNoun concept) {
        children.add(new CommonNounContainer(concept));
    }
        
    public ArrayList<CommonNounContainer> getChildren() {
        return children;
    }
    
    public CommonNoun getValue() {
        return myCommonNoun;
    }
    
    public boolean hasChildren() {
        if (children.size() > 0) return true;
        else return false;
    }
    
    public String toString() {
        return myCommonNoun.toString();
    }
} 


public class JSONContainer<T> {

    private T myObject;
    private ArrayList<JSONContainer<T>> children;
//    public Class<T> typeParameterClass;
    
    public JSONContainer() {

    }
    
    public JSONContainer(T anObject) {
        myObject = anObject;
        children = new ArrayList<JSONContainer<T>>();
    }

/*  public JSONContainer(T anObject,Class<T> typeParameterClass) {
        myObject = anObject;
        children = new ArrayList<JSONContainer<T>>();
        this.typeParameterClass = typeParameterClass;
    }
*/
    
    public void addChildren(ArrayList<JSONContainer<T>> newChildren) {
        children.addAll(newChildren);
    }

    public void addChild(T concept) {
        children.add(new JSONContainer<T>(concept));
    }
        
    public ArrayList<JSONContainer<T>> getChildren() {
        return children;
    }
    
    public T getValue() {
        return myObject;
    }
    
    public boolean hasChildren() {
        if (children.size() > 0) return true;
        else return false;
    }
    
    public String toString() {
        return myObject.toString();
    }
}

要求的其他课程:

public class CommonNoun extends Concept {
        
    /**
     * 
     */
    private static final long serialVersionUID = 6444629581712454049L;

    public CommonNoun() {
        super();
    }
    
    public CommonNoun(String name,ConceptID cidIn) {
        super(name,cidIn);
        this.form = ConceptDefs.COMMON_NOUN;
    }
    
}

public class Concept implements Serializable {
    
    /**
     * 
     */
    private static final long serialVersionUID = 2561549161503772431L;
    private ConceptID cid = null;
    private final String name;
    Integer form = 0;
    
//    ArrayList<ProperRelationship> myRelationships = null;

    
/*  @Deprecated
    public Concept(String name) {
        this.name = name;
    }*/
    
    public Concept() {
        name = "";
    }

    public Concept(String name,ConceptID cidIn) {
       // this(name);
        this.name = name;
        cid = cidIn;
    }

    /*
     * This should be over-ridden by any subclasses
     */
    public Integer getForm() {
        return form;
    } 
            
    public ConceptID getID() {
        return cid;
    }
    
    public void setID(ConceptID cidIn) {
        cid = cidIn;
    }
    
    //this doesn't make any sense.  Throw exception?
    public String getName() {
        return name;
    }

    public boolean isCommon() {
        return true;
    }
    
    /**
     *
     * @return
     */
    @Override
    public String toString() {
        return getName() + "(" + cid.toString() + ")";
    }
    
    public boolean equals(Concept other) {
        return ((getID().equals(other.getID())));
    }
    
}

public class ConceptID implements Serializable {

    long oid;
    
    public ConceptID() {
        oid = -1;
    }
    public ConceptID(long oid) {
        this.oid = oid;
    }
    
    public long getValue() {
        return oid;
    }
    
    /**
     *
     * @return
     */
    @Override
    public String toString() {
        return Long.toString(oid);
    }
    
    public Long toLong() {
        return Long.valueOf(oid);
    }

    
    public boolean equals(ConceptID other) {
        return (oid == other.getValue());
    }
    
    /**
     * Factory model for generating ConceptIDs
     * 
     * This one is here as a convenience as many IDs come in as a String from web POSTs
     * @param idAsString
     * @return
     */
    static public ConceptID parseIntoID(String idAsString) {
        ConceptID returnID = null;
        try {
            returnID = new ConceptID( Long.parseLong(idAsString) );
        } catch (Exception e) {
            System.err.println("Expected the string," + idAsString + ",to be Long parsable.");
            e.printStackTrace();
        }
        return returnID;

    }

解决方法

TL; DR

建议的修复方法...

  1. System.out.println( new Json( ).toJson( new JSONContainer<>( ... ) ) 查看 JSONContainer 正确 字符串格式s JSON
  2. result Json.fromJson(Class<T>,String) 输入参数设为 确定 1 中打印的相同格式。
    • 例如{myObject:{class:CommonNoun,cid:{oid:139},name:Jada Pinkett Smith,form:69},children:[{myObject:{class:CommonNoun,cid:{oid:666},name:Jaden Pinkett Smith,form:-666},children:[]},{myObject:{class:CommonNoun,cid:{oid:69},name:Willow Pinkett Smith,children:[]}]}


详细答案 ...

我的IDE对此短语不满意,请注意:

Type safety: The expression of type JSONContainer needs unchecked conversion to conform to JSONContainer

这是编译器警告您有关heap pollution的信息。 IDE只是翻译了此编译器警告(这是您在命令行上看到的)…

...Communicator.java uses unchecked or unsafe operations.
...Recompile with -Xlint:unchecked for details.

…进入IDE向您显示的更多用户友好消息。

这只是警告;没有错误。要使该警告消失,请将以下内容: JSONContainer<CommonNoun> typeContainer = ... 更改为以下内容: JSONContainer typeContainer = ...

执行后,我的错误日志显示为:

result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
com.badlogic.gdx.utils.SerializationException: Field not found: cid (java.lang.Object)...

最可能导致该错误的原因是-如错误消息所述-您的 JSONContainer 类或您的 CommonNoun 类没有要尝试反序列化的 cid 字符串中的 JSON 字段。

我能够以此重现该错误……

...
private static final String JADEN_AS_JSON = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}";

private static final String JADEN_FAILS_AS_ACTOR = "{jden:{class:CommonNoun,thing:HasBeen,cid:{oid:129} }}";

static public void main( String ... args ){
    
    out.printf( "%1$22s%n","foo");
    
    JSONContainer< CommonNoun > wtf = new JSONContainer< > ( );
    
    CommonNoun wtBrattyF = new CommonNoun( "Jaden Pinkett Smith","Hollywood","HasBeen" );
    
    wtf.setJden( wtBrattyF );
    
    out.printf( "%1$42s%n",wtf );
    
    Json jden = new Json();
    
    out.printf("%1$59s%n",jden.toJson( wtf ) );
            
    JSONContainer wtReifiableF = jden.fromJson(JSONContainer.class,JADEN_AS_JSON); /* This is fine */        
    
    out.printf("%1$59s%n",jden.toJson( wtReifiableF ) );
            
    JSONContainer/*< CommonNoun >*/ wtUnReifiableF = jden.fromJson( JSONContainer.class,JADEN_AS_JSON );
    
    wtUnReifiableF = jden.fromJson( JSONContainer.class,JADEN_FAILS_AS_ACTOR ); /* This causes the error you reported */
}
...

早期成功;但后来失败了...

JSONContainer [ jden: CommonNoun [ person: Jaden Pinkett Smith,place: Hollywood,thing: HasBeen ] ]
{jden:{class:CommonNoun,person:Jaden Pinkett Smith,thing:HasBeen}}
{jden:{class:CommonNoun,thing:HashBeen}}

Exception in thread "main" com.badlogic.gdx.utils.SerializationException: Field not found: cid (CommonNoun)
Serialization trace:
{}.jden.cid
jden (JSONContainer)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:893)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:902)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.fromJson(Json.java:829)
    at DeduperAnswer.main(DeduperAnswer.java:33)


我现在通过实验确认,给定存在 Cid 类……

public class Cid { 
    
    int oid;        

    /* ... getter and setter elided ... */
}

...并且鉴于存在 CommonNoun 类,该类 HAS A Cid ...

public class CommonNoun { 
    
    Cid cid;
    
    String name;
    
    int form;

    /* ... getters and setters elided ... */
}

…然后尝试从具有以下值的 JSONContainer 中反序列化 result ,将产生与您最初报告的完全相同的错误…

result = {"myObject":{"cid":{"oid":129},"children":[]}

如果您的实际 CommonNoun 类是像我的 stand-in 上面那样实现的(带有Cid字段 ),那么您需要使用格式如下的 json.fromJson(Class<?>,String) 字符串重试 result 呼叫

{myObject:{class:CommonNoun,children:[]}]}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-