简体   繁体   English

从 JSON 对象实例化一个类

[英]Instantiating a class from JSON object

I have a NodeJS WebSocket server in which I am required to create a Java client application for, however I haven't used JSON with Java in the past and I'm having some problems understanding how to create a class instance for the correct packet based on the type value in the Json object.我有一个 NodeJS WebSocket 服务器,我需要在其中创建一个 Java 客户端应用程序,但是我过去没有将 JSON 与 Java 一起使用,而且我在理解如何为基于正确的数据包创建类实例时遇到了一些问题在 Json 对象中的type值上。

To give you a little more insight, we have the Packet class which is abstract and then subclasses such as AuthenticationPacket .为了让您更深入地了解,我们有抽象的Packet类,然后是子类,例如AuthenticationPacket We have a Map<> that stores the Classes as such, Map<String, Class> So an example entry would be ("Authentication success", AuthenticationPacket.class)我们有一个Map<>来存储类, Map<String, Class>所以一个示例条目是("Authentication success", AuthenticationPacket.class)

Here's an example of the JSON data that we get back from the server.这是我们从服务器返回的 JSON 数据示例。

{
    "type": "Authentication success",
    "data": 
    {
        "username": "Hobbyist",
        "accountStatus": "USER"
    }
}

So my question is how would I create an new Class from the variables in the data field of the JSON response without having to pass in each parameter one at a time based on the type with a new AuthenticationPacket(...)所以我的问题是如何从 JSON 响应的data字段中的变量创建一个新类,而不必根据具有new AuthenticationPacket(...)的类型一次传递一个参数

Is there any way to do some sort of linking between the JSON and the class where it just creates a new instance of the class with all of the variables present in the data ?有没有办法在 JSON 和类之间进行某种链接,它只是创建类的新实例,其中包含data存在的所有变量?

Thanks谢谢

I hope i didn't get you wrong.我希望我没有误会你。

if you can convert json string to JSONObject ( I am using vert.x JsonObject )如果您可以将 json 字符串转换为 JSONObject (我正在使用 vert.x JsonObject )

PacketSErvice handles all Requests PacketSERVice 处理所有请求

 public class PacketService {

    private static PacketService instance; 

        private PacketService(){}
        public static PacketService newInstance(){

            if(instance == null) {
                instance = new PacketService();
            }
            return instance; 
        }

        public <T extends Packet> T handlePacket(Class<T> clazz, JSONObject data){
            return (T) clazz.newInstance().fromJson(data);
        }

      }

Packet interface数据包接口

 public interface Packet {  

            Packet fromJson(JSONObject object); 

            JSONObject asJson();

        }

And implement to your requests if you will have classes XPacket , YPacket , ZPacket如果您将拥有 XPacket 、 YPacket 、 ZPacket 类,并根据您的要求实施

Xpacket packet = PacketService.newInstance().handlePacket(XPacket.class,jsonData);

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

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