Why do we use JSON in android?
I am studing about JSON,and I recognized how I can use it and how it works.But I don't understand clearly , why do we use it in our project and programmes. If one of you describe the cause for me,I will get so glad ...
thanks for answering ...
Herewith you will learn how to use JSON in Android to fetch informaiton from server, what is JSON Object, JSONArray. It is a pretty common task in smartphone application development to query a website for some information, do a bit of processing, and present it to the user in a different form. There are two different main ways of going about this:
1.) Just download a whole webpage and use an HTML or XML parser to try and extract the information which you want.
2.) Some websites have API's which allow queries that instead of returning webpages, return XML, JSON, or some other way of presenting data.
Clearly, option 2 (if available) makes a lot more sense. Instead of downloading a large webpage (wasting data), parsing the entire thing (wasting battery), and then trying to analyze it (wasting your time going through often improperly written HTML), you can download much smaller, easier to manage text which conforms to XML, JSON, or whatever it is that the API provides. (I will be posting another tutorial about option 1 soon).
You might wonder why you would want to use JSON instead of XML for your smartphone application. After all, XML has been a much-ballyhooed technology buzzword for many years. There is, however, a good (and simple) reason. XML is (usually) bigger. The closing tags in XML do not exist in JSON, and therefore save you a few bytes for each tag that you don't need. JSON can generally express the same data using fewer characters, thus saving the phone from having to transfer more data every time there is a query to a website. This makes JSON a natural choice for quick and efficient website querying (for websites which offer it).
One such website is http://www.archive.org. Among many other things, archive.org allows people to upload recordings from concerts for other people to download for free. It's pretty awesome. They also have an API which allows you to query their system which will return results in XML, JSON, or a variety of other formats.
I am currently writing an application for browsing archive.org from your phone to find shows and then either download or stream the tracks. I'll show you how I do the first part (finding shows) using JSON and just a few lines of code.
First, you need your JSON query. I am going to query archive.org for “Lotus,” asking for a JSON result containing 10 items with their respective date, format, identifier, mediatype, and title. According to the archive.org search API, my query should look like this:
String archiveQuery = "http://www.archive.org/advancedsearch.php?q=Lotus&fl[]=date&fl[]=format&fl[]=identifier&fl[]=mediatype&fl[]=title&sort[]=createdate+desc&sort[]=&sort[]=&rows=10&page=1&output=json&callback=callback&save=yes";
Now that we have our query, we simly open an HTTP connection using the query, grab an input stream of bytes and turn it into a JSON object. On a side note, notice that I am using a BufferedInputStream because its read() call can grab many bytes at once and put them into an internal buffer. A regular InputStream grabs one byte per read() so it has to pester the OS more and is slower and wastes more processing power (which in turn wastes battery life).
InputStream in = null;String queryResult = "";
try { URL url = new URL(archiveQuery);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect();
in = httpConn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int read = 0; int bufSize = 512;
byte[] buffer = new byte[bufSize];
while(true)
{
read = bis.read(buffer);
if(read==-1){ break; }
baf.append(buffer, 0, read);
}
queryResult = new String(baf.toByteArray());
}
catch (MalformedURLException e)
{
// DEBUG
Log.e("DEBUG: ", e.toString());
}
catch (IOException e)
{
// DEBUG
Log.e("DEBUG: ", e.toString());
}
At this point, our JSON response is stored in the String queryResult. It looks kind of like this:
callback({ "responseHeader": {... *snip* ... }, "response": { "numFound": 1496, "start": 0, "docs": [{ "mediatype": "audio", "title": "The Disco Biscuits At Starscape 2010", "identifier": "TheDiscoBiscuitsAtStarscape2010", "format": ["Metadata", "Ogg Vorbis", "VBR MP3"] }, { "title": "Lotus Live at Bonnaroo Music & Arts Festival on 2010-06-10", "mediatype": "etree", "date": "2010-06-10T00:00:00Z", "identifier": "Lotus2010-06-10TheOtherStageBonnarooMusicArtsFestivalManchester", "format": ["Checksums", "Flac", "Flac FingerPrint", "Metadata", "Ogg Vorbis", "Text", "VBR MP3"] }, { "title": "Lotus Live at Mr. Smalls Theatre on 2006-02-17", "mediatype": "etree", "date": "2006-02-17T00:00:00Z", "identifier": "lotus2006-02-17.matrix", "format": ["64Kbps M3U", "64Kbps MP3", "64Kbps MP3 ZIP", "Checksums", "Flac", "Flac FingerPrint", "Metadata", "Ogg Vorbis", "Text", "VBR M3U", "VBR MP3", "VBR ZIP"] }, {... *snip* ...
We see that the information we want is stored in an array whose key is “docs” and is contained in an item called “response”. We can grab this information VERY easily using the JSONObject class provided by Android as shown below:
JSONObject jObject;try { jObject = new JSONObject(queryResult.replace("callback(", "")).getJSONObject("response"); JSONArray docsArray = jObject.getJSONArray("docs"); for (int i = 0; i < 10; i++) { if (docsArray.getJSONObject(i).optString("mediatype").equals("etree")) { String title = docsArray.getJSONObject(i).optString("title"); String identifier = docsArray.getJSONObject(i).optString("identifier"); String date = docsArray.getJSONObject(i).optString("date"); System.out.println(title + " " + identifier + " " + date); } }} catch (JSONException e) { // DEBUG Log.e("DEBUG: ", JSONString); Log.e("DEBUG: ", e.toString());}
The first thing that I do is create a JSONObject from “queryResult”, which is the JSON response from archive.org. Note that I remove “callback(” from the JSON string because, even though archive.org returns it, it should not actually be part of the JSON string (I realized this when I was catching JSONException errors).
After that, we are ready to do some JSON parsing. Since this is just a tutorial, I hardcode “10″ into the for loop because I requested 10 items. This would be a bad idea in production code (if you don't know why you are a huge noob and should not be writing production code). I only want items whose mediatype is “etree”, and for each of these items I print the title, identifier, and date.
Voila, you now know how to use JSON in Android.
source
Its a format that's easy for a human to read and write, yet still easy for a computer to parse. Its used where both people and machines will need to read data (like configuration files). Its also used for machines to send each other data in cases where ease of programming is more important than file size or parsing time (because JSON has built in parsers reading a JSON file is much easier to write quickly than parsing a binary format, and less fragile).
这些都是关于格式的。与传统的xml相比,它更轻量级。您可以使用它来序列化和传输结构化数据。请看这个问题。更详细地解释它。
链接地址: http://www.djcxy.com/p/47826.html上一篇: 什么是在Web应用程序中使用JSON?