Read JSON in Android
1. Read JSON content in JSON file
First, place the JSON file under directory assets:
Test.json
{"Programmers": [{"FirstName": "Brett", "LastName": "McLaughlin", "email": "AAAA"},{"firstName": "Jason", "LastName": " Hunter "," email ":" bbbb "},{" FirstName ":" Elliotte "," LastName ":" Harold "," email ":" CCCC "}]," authors ": [{" FirstName ":" Isaac "," LastName ":" Asimov "," Genre ":" Sciencefiction "},{" FirstName ":" Tad "," LastName ":" Williams "," Genre ":" Fantasy "},{" FirstName ":" Frank "," LastName ":" Peretti "," Genre ":" Christianfiction "}]," musicians ": [{" FirstName ":" Eric "," LastName ":" Clapton "," instrument ":" Guitar "},{" FirstName ":" Sergei "," LastName ":" Rachmaninoff "," Instrument ":" Piano "}]," Cat ":" Test "}
Read in Main.java
try {inputstreamreader isr=new InputStreamReader (Getassets (). Open ("Test.json"), "UTF-8");//Opening Test.json BufferedReader br=new BufferedReader (ISR);//Read ISR String line; StringBuilder builder=new StringBuilder (); while (line =br.readline ())!=null) {builder.append (line); } br.close (); Isr.close (); Jsonobject root=new Jsonobject (builder.tostring ()); System.out.println (Root.getstring ("cat")); Jsonarray Arry=root.getjsonarray ("programmers"); for (int i=0;i<arry.length (); i++) {Jsonobject lan=arry.getjsonobject (i); System.out.println ("----------------"); System.out.println ("FirstName:" +lan.getstring ("FirstName")); System.out.println ("LastName:" +lan.getstring ("LastName")); SYSTEM.OUT.PRINTLN ("Email" +lan.getstring ("email")); }} catch (IOException e) { E.printstacktrace (); LOG.E ("IO:", e.tostring ()); } catch (Jsonexception e) {e.printstacktrace (); LOG.E ("JSON:", e.tostring ()); }
Show Results:
To read the given JSON data:
You can attach the value directly
Jsonobject root=new Jsonobject (builder.tostring ()); replace-" jsonobject root=new jsonobject (" {' Programmers ': [{') FirstName ': ' Brett ', ' lastName ': ' McLaughlin ', ' email ': ' AAAA '}]};
2. Creating JSON-formatted data
JSONObject Root1=new Jsonobject (); try {root1.put ("cat", "it"); Jsonobject lan1=new jsonobject (); Lan1.put ("id", 1); Lan1.put ("IDE", "Android"); Lan1.put ("name", "Java"); Jsonobject lan2=new jsonobject (); Lan1.put ("id", 2); Lan1.put ("IDE", "Xcod"); Lan1.put ("name", "ios"); Jsonobject lan3=new jsonobject (); Lan1.put ("id", 3); Lan1.put ("IDE", "vs"); Lan1.put ("name", "C #"); Jsonarray array=new Jsonarray (); Array.put (LAN1); Array.put (LAN2); Array.put (LAN3); Root1.put ("Programmers", array); System.out.println (Root1.tostring ()); } catch (Jsonexception e) {e.printstacktrace (); }}
Display Result:
SOURCE Download: http://download.csdn.net/detail/agonie201218/8657765
Read and write JSON two JSON in Android