The generation and parsing of JSON data. First to download a JSON jar package on the Internet, I use Org.json
Demo Sample code:
Package Json;import Org.json.jsonarray;import Org.json.jsonobject;public class Main {/** * Generate JSON data */public static Strin G Createjson () {jsonobject json = new Jsonobject (); Json.put ("ClassId", 1); Class Json.put ("Grade", 1); Grade Jsonarray array = new Jsonarray (); Jsonobject O1 = new Jsonobject (); The first Student o1.put ("id", "101"); O1.put ("Name", "Zhangsan"); Array.put (O1); Jsonobject O2 = new Jsonobject () o2.put ("id", "102"), O2.put ("name", "Lisi"), O2.put ("score"); Array.put (O2); Json.put ("Student", array); return json.tostring ();} public static void Main (string[] args) {//output JSON data generated by String s = Createjson (); System.out.println (s);//Parse JSON data System.out.println ("Parse JSON data:"); Jsonobject obj = new Jsonobject (s); Generate Jsonobjectint classId = Obj.getint ("ClassId") based on JSON text; int grade = Obj.getint ("Grade"); Jsonarray array = (Jsonarray) obj.get ("Student"); for (int t=0; t<array.length (); ++t) {Jsonobject o = (jsonobject) array . Get (t); String id = o.getstring ("id"); String name = o.getstring ("NamE ");//int score = O.getint (" score "); Because there is no data, can not find the words will throw exception System.out.println (id+ "" +name);//+ "" +score);}}
Execution Result:
The generation and parsing of JSON data