Java Create and read JSON

Source: Internet
Author: User

I use Org.json to construct and parse JSON in Java, and the attachment is the corresponding Org.json.jar.

Here are two functions, one to create JSON, and one to construct the JSON from the text and parse it.

To create a JSON:

//construct JSON and output it PublicString Jsontest ()throwsjsonexception{jsonobject JSON=NewJsonobject (); Jsonarray jsonmembers=NewJsonarray (); Jsonobject Member1=NewJsonobject (); Member1.put ("LoginName", "Zhangfan"); Member1.put ("Password", "Userpass"); Member1.put ("Email", "[email protected]"); Member1.put ("Sign_date", "2007-06-12");        Jsonmembers.put (Member1); Jsonobject Member2=NewJsonobject (); Member2.put ("LoginName", "ZF"); Member2.put ("Password", "Userpass"); Member2.put ("Email", "[email protected]"); Member2.put ("Sign_date", "2008-07-16");      Jsonmembers.put (MEMBER2); Json.put ("Users", jsonmembers); returnjson.tostring (); }

Parsing JSON:

//construct JSON from String and resolve it. PublicString JsonTest2 ()throwsjsonexception{String jsonstring= "{\" users\ ": [{\" loginname\ ": \" zhangfan\ ", \" password\ ": \" Userpass\ ", \" email\ ": \" [Email protected]\ "},{\" Loginname\ ": \" zf\ ", \" password\ ": \" Userpass\ ", \" email\ ": \" [Email protected]\ "}]}"; Jsonobject JSON=NewJsonobject (jsonstring); Jsonarray Jsonarray=json.getjsonarray ("Users"); String Loginnames= "LoginName list:";  for(intI=0;i<jsonarray.length (); i++) {Jsonobject user=(jsonobject) jsonarray.get (i); String UserName= (String) user.get ("LoginName"); if(I==jsonarray.length ()-1) {Loginnames+=UserName; }Else{loginnames+=username+ ","; }    }    returnLoginnames;}
Jar Package: Json.jar

Java Create and read JSON

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.