Why do we use JSON in Android?

I'm studying JSON. I realize how I use it and how it works. But I don't know why we use it in projects and programs. If one of you describes the reason for me, I'll be happy

Thank you for your answer

resolvent:

Here, you will learn how to use JSON in Android to obtain information from the server, what is JSON object, jsonarray. It is a very common task to query some information, process it and present it to users in different forms in smartphone application development. There are two main ways:

1.) just download the entire web page and try to extract the information you want using an HTML or XML parser

2.) some websites have APIs that allow querying instead of returning web pages, returning XML, JSON or other ways of presenting data

Obviously, option 2 (if available) makes more sense. Instead of downloading large web pages (wasting data), parsing the entire content (wasting battery), and then trying to analyze it (wasting time and experiencing incorrect HTML writing) any content provided by XML, JSON or API. (I will publish another tutorial on option 1 soon)

You may wonder why JSON is used in smartphone applications instead of XML. After all, XML has been a much hyped technical buzzword for many years. However, there is a good (and simple) reason. XML is (usually) larger. The closing tag in XML does not exist in JSON, Therefore, several bytes are saved for each unnecessary tag. JSON can usually use fewer characters to express the same data, so that it does not have to transmit more data every time there is a query for the website. This makes JSON a natural choice for fast and effective website query (applicable to the website providing it)

One such website is http://www.archive.org. Among many other things, archive.org allows people to upload recordings from concerts for others to download for free. That's great. They also have an API that allows you to query their system, which will return results in XML, JSON or various other formats

I am currently writing an application to browse archive.org from my mobile phone to find programs, and then download or stream tracks. I will show you how to use JSON and a few lines of code to complete the first part (find programs)

First, you need JSON query. I will query the "Lotus" in archive.org to query the JSON results containing 10 items and their respective dates, formats, identifiers, media types and titles. According to the archive.org Search API, my query should be as follows:

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 we have a query. We use the query to easily open the HTTP connection, get the input byte stream and convert it into a JSON object. In addition, please note that I am using bufferedinputstream because its read() call can get multiple bytes at a time and put them into the internal buffer. A conventional InputStream reads one byte () at a time, Therefore, it has to adjust the operating system more and be slower and waste 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 string queryresult. It looks 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 with the keyword "docs" and contained in an item named "response". We can easily obtain this information by 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 I want to do is to create a JSON object from "queryresult", which is a JSON response from archive.org. Please note that I deleted "callback (") from the JSON string, because even if archive.org returns it, it should not actually be part of the JSON string (I realized this when capturing the JSON exception error)

After that, we are going to do some JSON parsing. Since this is just a tutorial, I hard code "10" into the for loop because I requested 10 projects. This is a bad idea in production code (if you don't know why you are a huge rookie, you shouldn't write production code). I just want mediatype to be "etree" projects, and for each project, I print the title, Identifier and date

Look, you now know how to use JSON in Android

source

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>