Determine user input data-type dynamically in JAVA

后端 未结 1 506
生来不讨喜
生来不讨喜 2021-02-14 23:43

I\'ve written the following code to determine the data-type of input entered by the user.

Update: Removed parsing into Float since a

相关标签:
1条回答
  • 2021-02-15 00:05

    My approach would be to let the framework do its thing, and use it to parse the input a generic way:

    Object obj = new org.json.JSONTokener(input).nextValue();
    if (obj instanceof JSONArray)
        return "JSONArray";
    
    if (obj instanceof JSONObject)
        return "JSONObject";
    
    if (obj instanceof Integer)
        return "Integer"
    ...
    

    Perhaps use a switch statement or a Map instead of a long list of if constructs. And catch JSONException for input that is not valid JSON.

    Could perhaps be simplified to return obj.getClass() or obj.getClass().getSimpleName() for almost identical functionality to what you have now.

    0 讨论(0)
提交回复
热议问题