Get JSON from a div in html

176 Views Asked by At

I have a hidden div which by JavaScript gets filled with json text. I need to find this div and read the json text from it. How can this be done?

<html>
    <div id="hiddenJSON"> 
        {
            "id":"1234",
            "Name":"Jonas",
            "Address":"Test Road 5",
            "Phone":"1234-1234-1234"
        }
    </div>
</html>
3

There are 3 best solutions below

0
On

It would be best to use a library for this such as JSoup. Check out this question about parsing html code

0
On

try below code :-

Pattern p = Pattern.compile(Pattern.quote("<div id=\"hiddenJSON\">") + "(.*?)" + Pattern.quote("</div>"));
Matcher m = p.matcher(text);
while (m.find()) {
  System.out.println(m.group(1));
}

But better solution is you have to receive data without html tag so talk with back end person.

0
On

Here is how i solved this:

result is the response from @JavascriptInterface

WebView Fragment

WebView wv = ...
wv.addJavascriptInterface( this, "android" );
wv.loadUrl( "javascript:android.showHTML(document.getElementById('hiddenJSON').innerHTML);" );

Interface in my WebView Fragment

@JavascriptInterface
public void showHTML( String result ) {

    // handle JSON (result)

}

Problem: I had to get the result from my WebView in order to get the JavaScript to run (filling this hidden div with JSON).