First prepare a JSON-formatted string
* String jsonstr = "{object:{persons:" +
"[{name: ' hehe ', Image: ' Http://10.0.159.132:8080/Web/s1.png '}, ' +
"{name: ' haha ', Image: ' Http://10.0.159.132:8080/Web/s1.png '}," +
"{name: ' hehe ', Image: ' Http://10.0.159.132:8080/Web/s2.jpg '}]}}";
* Then define a person class
*
*
1 classperson{2 PrivateString name,image;3 4 PublicString GetName () {5 returnname;6 }7 8 Public voidsetName (String name) {9 This. Name =name;Ten } One A PublicString getImage () { - returnimage; - } the - Public voidsetimage (String image) { - This. Image =image; - } + -}
Here is a JSON-parsed program code
1 classMyday17xml {2 //JSON string3 StaticString jsonstr = "{object:{persons:" +4"[{name: ' hehe ', Image: ' Http://10.0.159.132:8080/Web/s1.png '}, ' +5"{name: ' haha ', Image: ' Http://10.0.159.132:8080/Web/s1.png '}," +6"{name: ' hehe ', Image: ' Http://10.0.159.132:8080/Web/s2.jpg '}]}}";7 8 Public Static voidMain (String []args)throwsjsonexception{9List<person> list=jsonstrtolist (JSONSTR);Ten System.out.println (List.size ()); One } A /** - * - * the * - */ - Public StaticList<person> jsonstrtolist (String jsonstr)throwsjsonexception{ -List<person> list=NewArraylist<person>(); + - //get the most external JSON object through a string +Jsonobject jsonobj=NewJsonobject (JSONSTR); A //get an internal object by property name atJsonobject jsonpersons=jsonobj.getjsonobject ("Object"); - //get a JSON object group -Jsonarray Arr=jsonpersons.getjsonarray ("persons"); - for(intI=0;i<arr.length (); i++){ - //loop the object and pass the GetString ("property name") to get the value -Jsonobject tempjson=Arr.getjsonobject (i); inPerson person=NewPerson (); - toPerson.setname (tempjson.getstring ("name")); +Person.setimage (tempjson.getstring ("image")); - List.add (person); the } * returnlist; $ Panax Notoginseng } - the}
JSON parsing in Java