How can I get a Javascript variable value in Java?

前端 未结 2 378
迷失自我
迷失自我 2021-01-19 04:47

In my current project I have to read a JavaScript file from the web and extract an object from it. The variable can vary from time to time, so I have to read it instead of h

相关标签:
2条回答
  • 2021-01-19 05:50

    There are many libraries in Java to parse the JSON. There is a list on JSON.org

    Read the file with Java

    import org.json.JSONObject;
    
    URL url = new URL("http://example.com/foo.js");
    InputStream urlInputStream = url.openStream();
    JSONObject json = new JSONObject(urlInputStream.toString());  
    
    0 讨论(0)
  • 2021-01-19 05:53

    Finally code it myself.

    //remove comments
    private String removeComment(String html){
        String commentA = "/*";
        String commentB = "*/";
        int indexA, indexB;
        indexA = html.indexOf(commentA);
        indexB = html.indexOf(commentB);
        while(indexA != -1 && indexB != -1 ){
            html = html.substring(0, indexA) + html.substring(indexB + commentB.length());
            indexA = html.indexOf(commentA);
            indexB = html.indexOf(commentB);
        }
        return html;
    }
    
        //find variable with name varName
    private String findVar(String varName, String html, char lBrace, char rBrace){
        String tmp = html.substring(html.indexOf(varName));
        tmp = tmp.substring(tmp.indexOf(lBrace));
    
        int braceCount = 0;
        int index = 0;
        while(true){
            if(tmp.charAt(index) == lBrace){
                braceCount ++;
            }else if(tmp.charAt(index) == rBrace){
                braceCount --;
            }
            index ++;
            if(braceCount == 0){
                break;
            }
        }
        return tmp.substring(0, index);
    }
    
    0 讨论(0)
提交回复
热议问题