Sid
Sid

Reputation: 234

JSON: Create a web page with JSON data

Firstly, I am extremely new to JSON. I have been reading as much as I can on it. While I get the concept, implementing it is a different deal altogether for me.

So, I have an app which reads and displays data from JSON web pages. For instance, I can extract the time that is being shown in this website: http://date.jsontest.com/

Using the HTML from this website, I added the JSON Object to my HTML page in the following manner:

<html>
<body>
<pre>
{
   "score": "30-20"
}
</pre>
</body>
</html>

However, the app now throws a JSON exception everytime I try to retreive the score.

My question is, 'Is adding a JSON Object to the pre tag in an HTML page the correct way of creating a JSON Object on a web page?'

If not, what is the correct way to do it?

EDIT: This is is the code I am using in java to retrieve the JSON data:

    StringBuilder url = new StringBuilder(URL);
    HttpGet get = new HttpGet(url.toString());
    HttpResponse r = client.execute(get);
    int status = r.getStatusLine().getStatusCode();
    if(status==200){
        HttpEntity e = r.getEntity();
        String data = EntityUtils.toString(e);
        //JSONArray timeline = new JSONArray(0);
        JSONObject last = new JSONObject(data);
        return last;
    }
    else{
        Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
        return null;
    }

The try statement:

try {
            json = lastTweet();
            return json.getString("time");
            //return "Oh Well";
        } 

Thanks.

Upvotes: 0

Views: 17726

Answers (2)

vp_arth
vp_arth

Reputation: 14992

Use something like this:

response.setContentType("application/json");
PrintWriter out = response.getWriter();
String json = "{\"data\": \"test\"}";
out.print(json);
out.flush();

on your dataserver

Upvotes: 1

Sunny Patel
Sunny Patel

Reputation: 8077

Your application should send the Content-type: application/json header and should only output the string representation of the data itself, so that your entire page is just:

{
   "score": "30-20"
}

and nothing more. The example that you gave follows the same procedure if you check the response headers and view the source code of that page.

The reason your parser is failing is because the page starts with <, when the first non-whitespace character should be {.

Upvotes: 1

Related Questions