Android parsing JSON data _android

Source: Internet
Author: User
Tags tojson

The use of Jsonobject

Use of JSON objects:

String content = "{' username ': ' linux ', ' Password ': ' 123456 '}";
Jsonobject jsonobject = new Jsonobject (content);
String username = jsonobject.getstring ("username");
String Password = jsonobject.getstring ("password");

Second, use of JSON arrays:

String jsoncontent = "[{' User ': ' Liu Li Zhucheng ', ' Age ':", ' Femal ': true}, "
            +" {' User ': ' Chen ', ' age ': ', ' Femal ': false}] "; 
   jsonarray Jsonarray = new Jsonarray (jsoncontent);
for (int i = 0; i < jsonarray.length (); i++) {
   Jsonobject object = Jsonarray.getjsonobject (i);
   System.out.print (object.getstring ("user") + "");
   System.out.print (Object.getint ("age") + "");
   System.out.print (Object.getboolean ("femal") + "");
   System.out.println ();
}

Three, the JSON array is mixed with the JSON object

String jsonstring = "[{' User ': ' tomhu ', ' age ':" + "' info ': {' adress ': ' Hubai ', ' sex ': ' Femal '}},"
          + "{' User ': ' C Hen ', ' age ': "+" ' info ': {' adress ': ' Hunan ', ' sex ': ' Male '}}] ";
Jsonarray jsonarrays = new Jsonarray (jsonstring);
for (int i = 0; i < jsonarrays.length (); i++) {
  Jsonobject objects = Jsonarrays.getjsonobject (i);
  System.out.print (objects.getstring ("user") + "");
  System.out.print (Objects.getint ("age") + "");
  System.out.print (Objects.getjsonobject ("info"). GetString ("adress") + "");
  System.out.print (Objects.getjsonobject ("info"). getString ("sex") + "");
  System.out.println ();
}

Iv. storing objects in the JSON array

person who = new person ();
Person.setusername ("Linux");
Person.setpassword ("123456");
Jsonarray Jsonarray = new Jsonarray ();
Jsonarray.put (0, person);
Jsonarray.put (1, "I Love You");

String username = jsonarray.getjsonobject (0). getString ("username"); Wrong wording person
user = (person) jsonarray.get (0);
System.out.println ("Username:" + user.getusername ());

The principle of Jsonobject

Storage and removal of Jsonobject

One, the jsonobject inside maintains a linkedhashmap, when generates a parameter-free jsonobject, the essence is initializes a map:

Private final linkedhashmap<string, object> Namevaluepairs;
Public Jsonobject () {
  namevaluepairs = new linkedhashmap<string, object> ();
}

When Jsonobject adds data, it essentially stores the data's key-value pairs in the above map:

Public Jsonobject put (String name, Boolean value) throws Jsonexception {
  namevaluepairs.put (checkname (name), value) ;
  return this;
}

Third, from the Jsonobject to remove data, it is easy to think of is removed from the map:

Public String getString (string name) throws Jsonexception {
  object = Get (name),//Get () method executes Object result = N Amevaluepairs.get (name);
  String result = json.tostring (object);
  if (result = = null) {
    throw Json.typemismatch (Name, object, "String");
  }
  return result;
}

The parsing process of Jsonobject

One, Jsonobject also has a constructor with parameters: It is commonly used to pass a string parameter

Public Jsonobject (String json) throws Jsonexception {This
  (new Jsontokener (JSON));
}

Second, follow in, found that the main implementation of the Jsontokener NextValue () method, in this method is mainly to analyze the data;

Public Object NextValue () throws jsonexception {
  int c = nextcleaninternal ();
  Switch (c) {
    case-1:
      throw SyntaxError ("End of input");

    Case ' {': return
      readobject ();

    Case ' [': Return
      Readarray ();

    Case '/': Case
    ' ': Return
      nextstring ((char) c);

    Default:
      pos--;
      return readliteral ();
  }


In the Nextcleaninternal method, it will parse the character-by-letter from beginning to end, and do some processing for some characters. such as spaces, line breaks, escape characters, and so on!
When parsing to [represents the beginning of a read of an object, when parsing to {represents an array of reads

Third, in the ReadObject method, still call the Nextcleaninternal () method, the parsed characters, down to the parse to}. Important code is posted below

INT-A-nextcleaninternal (); The parsed character
if (A/c = '} ') {return result
  ;
} else if (!=-1) {
  pos--
}
.......
while (true) {
  Object name = NextValue ();//Parse get key
  
  int separator = nextcleaninternal ();
  if (separator!= ': ' && separator!= ' = ') {
    throw syntaxerror ("expected ': ' after" + name);
  }
  if (Pos < In.length () && In.charat (pos) = ' > ') {
    pos++
  }

  Result.put ((String) name, NextValue ()); The parsed key value pair is stored in the map

  switch (nextcleaninternal ()) {case
    '} ': return result
      ;
    Case '; ': Case
    ', ':
      continue;
    Default:
      throw SyntaxError ("Unterminated object");
  }


Four, the NextValue method comparison key, it circulates the most work which parses! In NextValue, there is a readliteral method, which is processed for some types, and the result is resolved:

Private Object Readliteral () throws jsonexception {String literal = nexttointernal ("{}[]/\\:,=;# \t\f");
  if (literal.length () = = 0) {Throw syntaxerror ("expected literal value");
  else if ("null". Equalsignorecase (literal)) {return jsonobject.null;
  else if ("true". Equalsignorecase (literal)) {return boolean.true;
  else if ("false". Equalsignorecase (literal)) {return boolean.false;
    }/* Try to parse as a integral type ... */if (Literal.indexof ('. ') = = 1) {int base = 10;
    String number = literal;
      if (Number.startswith ("0x") | | number.startswith ("0X")) {number = number.substring (2);
    base = 16;
      else if (Number.startswith ("0") && number.length () > 1) {number = number.substring (1);
    base = 8;
      try {Long longvalue = Long.parselong (number, base);
      if (longvalue <= integer.max_value && longvalue >= integer.min_value) {return (int) Longvalue;
} else {        return longvalue; The catch (NumberFormatException e) {* * * * happens for integral numbers greater than * L Ong. Max_value, numbers in exponential form (5e-10) and * unquoted strings.
       Fall through to try floating point.
  */}}/* ... next try to parse as a floating point ... * * try {return double.valueof (literal); The catch (NumberFormatException ignored) {}/* ... finally give up. We have an unquoted string */return new string (literal);

 A new string avoids leaking memory}

V. As for Jsonarray parsing and Jsonobject parsing process is the same, it maintains a list:

Private final list<object> values;
Public Jsonarray (Jsontokener readfrom) throws Jsonexception {
  object = Readfrom.nextvalue ();
  If (object instanceof Jsonarray) {
    values = (Jsonarray) object). values;
  } else {
    throw json.typemismatch ( Object, "Jsonarray");
  }

The use of Gson

First, we in the test to add a person class to facilitate testing:

Package com.tomhu.test;

public class Person {
  private String name;
  private int age;

  Public String GetName () {return
    name;
  }
  public void SetName (String name) {
    this.name = name;
  }
  public int getage () {return age
    ;
  }
  public void Setage (int age) {
    this.age = age;
  }
}

Second, Gson convert objects to JSON format

Gson Gson = new Gson ();
person who = new person ();
Person.setname ("Linux");
Person.setage (a);
String str = Gson.tojson (person);
System.out.println (str);

Printing results: {"name": "Linux", "Age": 23}

Third, Gson the JSON format into an object

String Jsondata = "{' name ': ' Liu Li Zhucheng ', ' Age ':}";
Person person = Gson.fromjson (Jsondata, person.class);
System.out.println (Person.getname () + "," + person.getage ());

Printed result: Liu Li Zhucheng, 19

Iv. Gson the list object into JSON format:

Gson Gson = new Gson ();
list<person> persons = new arraylist<person> ();
for (int i = 0; i < 2; i++) {person
   p = new Person ();
   P.setname ("name" + i);
   P.setage (i * 5);
   Persons.add (P);
}
String str = gson.tojson (persons);
System.out.println (str);

Print Result: [{' Name ': ' NAME0 ', ' age ': 0},{' name ': ' name1 ', ' Age ': 5}]

V. Gson the JSON format into a list object:

Gson Gson = new Gson ();
String str = "[{' name ': ' Linux ', ' Age ': 10},{' name ': ' Huhx ', ' Age ':}]";
list<person> PS = Gson.fromjson (str, new typetoken<list<person>> () {}.gettype ());
for (int i = 0; i < ps.size (); i++) {person person
  = ps.get (i);
  System.out.print ("Name:" + person.getname () + "Age:" + person.getage ());
}

Print Result: Name:linux age:10 name:huhx age:22

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: [email protected] 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.