【问题标题】:How to convert a json string to an array of known types using Gson?如何使用 Gson 将 json 字符串转换为已知类型的数组?
【发布时间】:2016-06-20 18:16:17
【问题描述】:

我有一个请求类

class Request{
     String serviceName ;
     String methodName;
     Serializable[] arguments;
}

这表示在服务器上执行特定方法的请求。

参数是一个随机的完全可序列化对象的数组。

现在我使用

对其进行序列化
Request req = new Request("serviceName" , "methodName" , Serializable...) 
// all arguments are specified through the elipsis and stored in the arguments array
Gson gson = new Gson() ;

gson.toJson(request) ;

现在我正在尝试反序列化 - 问题很明显,因为 Gson 不知道数组中每个元素的类型。

所以要反序列化我有一个

Class<?>[] argTypes = new Class<?>[equalNumberToArguments]() ;
// This type array is filled with types that I know match the arguments array in request. 

现在我有一个自定义的反序列化器

class RequestDeserializer implements JsonDeserializer<Request> {

        Class<?>[] paramTypes = null ;

        // The types matching the arguments array are specified through the          constructor here. 
        RequestDeserializer(Class<?>[] types){
            paramTypes = types ;
        }

        @Override
        public Request deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {

            final JsonObject jsonObject = json.getAsJsonObject();

            String s = jsonObject.get("serviceName").getAsString(); 
            String m = jsonObject.get("methodName").getAsString();
            JsonElement element = jsonObject.get("arguments") ;

            if (element.isJsonArray()){
                JsonArray array = element.getAsJsonArray() ;

                // - how do I implement retrieval of each json object from   
                array here ?
            }

            return null;
        }

    }

【问题讨论】:

    标签: java arrays json gson deserialization


    【解决方案1】:

    这是我正在使用的解决方案

    class RequestDeserializer implements JsonDeserializer<Request> {
    
        JsonElement element = null ;
        JsonElement argumentJson = null ;
        Class<?> types = null ;
    
        public RequestDeserializer(Class<?> tps){
            types = tps ;
        }
    
        public Object[] getArguments(){
    
            if (types.length == 0)
                return null ;
    
            Object[] arguments = new Object[types.length] ;
    
            if (argumentJson != null && argumentJson.isJsonArray()){
    
                JsonArray array = argumentJson.getAsJsonArray() ;
    
                for ( int i=0 ; i < types.length ; i++){
    
                    JsonElement arrayEle = array.get(i) ;
    
                    Gson gson = new Gson() ;
    
                    arguments[i] = gson.fromJson(arrayEle, types[i]) ;
                }
            }
            return arguments;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 2012-03-05
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多