The generation and parsing of JSON data

Source: Internet
Author: User

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

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.