Json Django PDF
Json Django PDF
In Lab 2, we discussed how to parse data in the JSON format on Android, but we said nothing about
how to create new JSON data. Now that we have the tools that allow us to build web applications, we
can also think about building our own web services on top of Django that use data in the JSON format
both as a way to expose data for consumption by Android applications, but also as a way to receive data
from Android apps. We'll consider each of these tasks in turn.
respectively) and construct the JSON Java objects. These may then be converted to a JSON String
using the toString() method of the JSON Java object. For example:
import
import
import
import
java.util.ArrayList;
java.util.HashMap;
org.json.JSONArray;
org.json.JSONObject;
endArray() marks the end of a JSON array previously started with array().
endObject() marks the end of a JSON object previously started with object().
Two other methods are used to populate these compound data structures:
key(String string) Add a new key to a JSON object previously started with object().
(NOTE: the previous method should NOT have been array() or key())
array() and object() may also be used to mark the beginning of nested array or object values
(instead of value()).
All of these methods return the same JSONWriter instance, so they may be chained.
import org.json.JSONStringer;
JSONStringer s = new JSONStringer();
s.array().value(1).value(2).endArray();
String jsonString = s.toString();
# jsonString is the string "[1, 2]"
s = new JSONStringer();
s.object().key("key1").value("string")
.key("key2").value(2.5).endObject();
jsonString = s.toString();
# jsonString is the string "{"key1":"string","key2":2.5}"
This string may then be sent to your Django web service.
HttpURLConnection c;
OutputStream os;
byte[] data = jsonData.getBytes();
try {
URL url = new URL("http://www.example.com/example_upload_site");
c = url.openConnection();
c.setDoOutput(true);
c.setFixedLengthStreamingMode(data.length);
os = c.getOutputStream();
} catch (MalformedURLException e) {
// If the URL is not a valid URL.
} catch (IOException e) {
// If an error prevented opening or writing to the stream.
}
try {
os.write(data);
} catch (IOException e) {
// If an error prevented opening or writing to the stream.
} finally {
// This clause ensures that disconnect() is always run last,
// even after an exception is caught. You should wrap
// reader.readLine() like this too.
c.disconnect();
}
Note that this code will upload exactly the contents of the jsonData variable, and thus it is not suitable
for submitting form data (such as to an HTML form). If we wish to read the response data from the
server after sending our data, we need only get the InputStream of the connection after we have
written all of the data, and read from that stream prior to disconnecting.