Android JSON generation and parsing examples

Source: Internet
Author: User

The definition of JSON:

A lightweight data interchange format with good readability and easy-to-write features. The industry's mainstream technology provides a complete solution (somewhat like regular expressions, which is supported in most languages today), enabling data exchange between different platforms. JSON uses a high-compatibility text format, and also has a similar behavior to the C language system.

JSON Vs XML

The data readability of 1.JSON and XML is basically the same

2.JSON and XML also have a wealth of analytic means

3.JSON data is small in size relative to XML

4.JSON interaction with JavaScript is more convenient

5.JSON is less descriptive of data than XML

6.JSON is much faster than XML

JSON parsing classes provided by android2.3

The JSON parsing part of Android is under package Org.json, mainly in the following categories:

Jsonobject: Can be thought of as a JSON object, which is the basic unit in the system for json definition, which contains a pair of tostring () method output value key and value are colon ":" delimited). Its operation format for internal jsonobject instance, referencing the internal The put () method adds a value: New Jsonobject (). Put ("JSON", "Hello, world!"), between key and value is a comma Span lang= "en-us" > "," delimited. value types include: boolean, jsonarray, Jsonobject, number, string or default jsonobject.null object.

Jsonstringer:json text Building class, according to the official explanation, this class can help to create JSON text quickly and conveniently. The biggest advantage is that you can reduce program exceptions due to malformed formatting, and referencing this class automatically creates JSON text in strict accordance with the JSON syntax rules (syntax rules). Each Jsonstringer entity can only be created with one JSON text: The biggest advantage is that you can reduce program exceptions due to malformed formatting, and referencing this class automatically creates JSON text in strict accordance with the JSON syntax rules (syntax rules). Each Jsonstringer entity can only create one JSON text.

Jsonarray: It represents an ordered set of values. Converting it to a string output (toString) is performed in the form of a square bracket, separated by a comma "," (for example: [Value1,value2,value3], you can personally use the short code to understand its format more intuitively). The inside of this class also has query behavior, both get () and opt () can return the specified value through the index index, and the put () method is used to add or replace values. Similarly, the value type of this class can include: Boolean, Jsonarray, Jsonobject, number, string, or Default value Jsonobject.null object.

Jsontokener:json Parsing class
Exceptions used in Jsonexception:json

Here's an example of JSON generation and parsing:

[Java]View Plaincopy
  1. /**
  2. * JSON operation class.
  3. * @author E
  4. */
  5. Public class Jsonutil {
  6. /** 
  7. * Converts an array to JSON-formatted data.
  8. * @param stonelist Data source
  9. * @return data in JSON format
  10. */
  11. public static String Changearraydatetojson (arraylist<stone> stonelist) {
  12. try {
  13. Jsonarray array = new Jsonarray ();
  14. Jsonobject object = new Jsonobject ();
  15. int length = Stonelist.size ();
  16. For (int i = 0; i < length; i++) {
  17. Stone stone = stonelist.get (i);
  18. String name = Stone.getname ();
  19. String size = Stone.getsize ();
  20. Jsonobject stoneobject = new Jsonobject ();
  21. Stoneobject.put ("name", name);
  22. Stoneobject.put ("size", size);
  23. Array.put (Stoneobject);
  24. }
  25. Object.put ("stones", array);
  26. return object.tostring ();
  27. } catch (Jsonexception e) {
  28. E.printstacktrace ();
  29. }
  30. return null;
  31. }
  32. /** 
  33. * Convert JSON to an array and return.
  34. * @param Json
  35. * @return arraylist<stone>
  36. */
  37. public static arraylist<stone> Changejsontoarray (String Json) {
  38. arraylist<stone> gamelist = new arraylist<stone> ();
  39. try {
  40. Jsonobject jsonobject = new Jsonobject (Json);
  41. if (!jsonobject.isnull ("stones")) {
  42. String astring = jsonobject.getstring ("stones");
  43. Jsonarray Ajsonarray = new Jsonarray (astring);
  44. int length = Ajsonarray.length ();
  45. For (int i = 0; i < length; i++) {
  46. Jsonobject Stonejson = Ajsonarray.getjsonobject (i);
  47. String name = stonejson.getstring ("name");
  48. String size = stonejson.getstring ("size");
  49. Stone stone = New Stone ();
  50. Stone.setname (name);
  51. Stone.setsize (size);
  52. Gamelist.add (stone);
  53. }
  54. }
  55. } catch (Exception e) {
  56. E.printstacktrace ();
  57. }
  58. return gamelist;
  59. }
  60. }

After writing a good method, you can refer to it as follows:

[Java]View Plaincopy
  1. Import java.util.ArrayList;
  2. Import android.app.Activity;
  3. Import Android.os.Bundle;
  4. Import Android.util.Log;
  5. Import Android.view.View;
  6. Public class Mainactivity extends Activity {
  7. @Override
  8. protected void OnCreate (Bundle savedinstancestate) {
  9. super.oncreate (savedinstancestate);
  10. Setcontentview (R.layout.main);
  11. Findviewbyid (r.id.test). Setonclicklistener (new View.onclicklistener () {
  12. @Override
  13. public void OnClick (View v) {
  14. Init ();
  15. }
  16. });
  17. }
  18. private void init () {
  19. arraylist<stone> list = new arraylist<stone> ();
  20. For (int i = 0; i < 5; i++) {
  21. Stone stone = New Stone ();
  22. Stone.setname ("Name" +i);
  23. Stone.setsize ("Size" + i);
  24. List.add (stone);
  25. }
  26. String json = Jsonutil.changearraydatetojson (list);
  27. LOG.E ("JSON", JSON);
  28. }
  29. }


Looking at the log again, we see the resulting JSON data:

[Java]View Plaincopy
    1. {"stones": [{"size":"Size0","name": "NAME0"},{"size": "Size1","name":"Name1"} {"size":"Size2","name": "Name2"},{"size":"Size3","name":"Name3"},{ "size":"Size4","name":"Name4"}]}


The above is how to generate JSON data, parsing please refer to the second method.

Android JSON generation and parsing examples

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.