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

How do I read this Generics correctly from JSON?

我对我的第一个泛型容器有相当的信心,但仍然坚持如何在客户端表达转换。这就是我参与学习 <T> 东西之前的工作方式:

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

我考虑过为每个 class 创建一个不同的容器,这似乎不是一个好的设计。下面是我在新的泛型容器中读取的更新的、无效的尝试:

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

我的 IDE 不关心这个措辞,注意:

Type safety: The expression of type JSONContainer needs unchecked conversion to conform to 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.handleHttpResponse(Communicator.java:95)
    at com.badlogic.gdx.net.NetJavaImpl.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 和剥离 class 信息。我试图遵循的其中一个与上面的转换无关,认为在构造期间将 T class 作为私有变量添加到容器中:

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

但我 运行 遇到了类似的语法问题,试图正确引用 class,只是在过程中的不同位置。我也怀疑我是否可以在告诉 JSON 如何 class 验证文件中的信息之前从 JSON 文件中读取这个 class 变量。

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. 

我可能已经有了 deduper 提交的可行答案,但是,根据要求,这里有 CommonNounContainer 和 JSONContainer classes:

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();
    }
}

额外 class 请求:

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<>( ... ) )正确的字符串格式JSONContainerJSON.
  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,form:69},children:[]}]}


长答案

My IDE doesn't care for this phrasing, noting:

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.

…进入 user-friendly 消息 IDE 给你看。

这只是一个警告;不是错误。要使该警告消失,请将此更改:JSONContainer<CommonNoun> typeContainer = ... 为:JSONContainer typeContainer = ...

When executed, my err log reads:

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

该错误最可能的原因是 — 如错误消息所述 — 您的 JSONContainer class 或您的 CommonNoun class 没有 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,person:Jaden,place:Hollywood,thing:HasBeen, cid:{oid:129} }}";

static public void main( String ... args ){
    
    out.printf( "%1s%n", "foo");
    
    JSONContainer< CommonNoun > wtf = new JSONContainer< > ( );
    
    CommonNoun wtBrattyF = new CommonNoun( "Jaden Pinkett Smith", "Hollywood", "HasBeen" );
    
    wtf.setJden( wtBrattyF );
    
    out.printf( "%1s%n", wtf );
    
    Json jden = new Json();
    
    out.printf("%1s%n", jden.toJson( wtf ) );
            
    JSONContainer wtReifiableF = jden.fromJson(JSONContainer.class, JADEN_AS_JSON); /* This is fine */        
    
    out.printf("%1s%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,place:Hollywood,thing:HasBeen}}
{jden:{class:CommonNoun,person:Jaden,place:Hollywood,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)


现在我已经通过实验证实了给定Cidclass…

的存在
public class Cid { 
    
    int oid;        

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

… 并且给定 CommonNoun class 的存在 有一个 Cid

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

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

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

result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}

如果你的实际 CommonNoun class 像我上面的 stand-in 那样实现(带有 Cid 字段),那么您需要使用 [= 重试 json.fromJson(Class<?>, String) 调用22=] 字符串格式如...

{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,form:69},children:[]}]}