如何将对象存储为其余web服务的字符串参数中的字符串

时间:2015-08-31 13:34:18

标签: java json web-services rest

我正在使用REST Web服务,我是否可以在webservice中拥有灵活的字符串参数,该参数可以接受存储为字符串的任何对象。

例如,我有这个样本RequestJson:

public class RequestJSON {
    String username;
    String password;
    String data;
}

在data参数中我想接受任何json对象,

@Path("/rest")
public class RESTWebservice {
    @POST
    @Path("/request")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public ResponseJSON sampleWeb(RequestJSON requestJson) {
        logger.info(requestJson.toString());
    }
}

我们如何让webservice接受在请求Json的数据参数中发送的任何json:

例如:

{
"username":"abc",
"password":"xyz",
"data":{"number":"4","input":"","msg":{"msgArr":["hello","test"]}},
}

有可能吗?

1 个答案:

答案 0 :(得分:0)

是的,有可能:

import java.util.List;

public class Main {

    enum DATATYPE {
        STRING,
        FLOAT,
        INTEGER,
        BOOLEAN; // could add lists but then it gets nasty because you have to have a delimiter
    }

    class ColectionOfData {
        List<DATA> data;
    }

    class DATA  { 
        String name;
        DATATYPE datatype; // form should inform of the data type
        String data;

        public DATA(String name, DATATYPE datatype, String data) {
            this.name = name;
            this.datatype = datatype;
            this.data = data;
        }

        public Object convert() {
            switch(datatype) {
            case BOOLEAN:
                return Boolean.parseBoolean(data);
            case FLOAT:
                return Float.parseFloat(data);
            case INTEGER:
                return Integer.parseInt(data);
            case STRING:
                return data;
            default:
                return null;
            }
        }
    }

}

但它并不漂亮。你可以减少丑陋,但它总是很难看。