In the previous section we learned the parsing of XML files, and then we learned about the parsing of JSON files. JSON classes are also available in LIBGDX to help us parse the file, the most common method being Fromjson (java.lang.Class type, filehandle file) By this method we must first define an inner class to abstract the representation of the JSON file.
{"Name":"David","Experience":2534,"Strength":6,"Dexterity":8,"Intelligence":6,"Items": [ {name:"Iron-sword", Number:1}, {name:"Wooden-shield", Number:1}, {name:"Leather-armor", Number:1}, {name:"Leather-boots", Number:1}, {name:"Healing-potion", Number:3}, {name:"Poison-herbs", Number:2} ]}
As we can see from the JSON file above, the JSON file contains the object name, experience, strength, dexterity, dexterity, intelligence, items, a total of 7 properties, So we need to define a Charactor.class class to accommodate these 7 properties. At the same time we can know that the items contain 2 attributes: Name, number, so we need to define a class item.class to accommodate these 7 properties.
The following is a specific code implementation:
Public classJsontest extends Applicationadapter {@Override Public void Create() {JSON JSON =NewJson (); Json.setelementtype (Character.class,"Items", Item.class);//Specify the item data type in characterCharacter Character = Json.fromjson (Character.class, Gdx.files.Internal("Character.json"));//Create a Charactor object from the JSON fileSystem. out. println (character);//System.out.println ("Dexterity:" + character.dexterity); To access a single attribute, you need to create a corresponding classSystem. out. println (); System. out. println ("====================="); System. out. println ("serializing character"); System. out. println ("====================="); System. out. println (Json.prettyprint (Json.tojson (character))); } Public Static classItem {PrivateString name;Private intNumber @Override PublicStringtoString() {returnName +"("+ number +")"; } } Public Static classCharacter {PrivateString name ="";Private intExperience =0;Private intStrength =1;Private intDexterity =1;Private intIntelligence =1; Publicarray<item> items =NewArray<item> (); @Override PublicStringtoString() {Stringstring=NewString ();string+="Name:"+ name +"\ n";string+="Experience:"+ Experience +"\ n";string+="Strength:"+ Strength +"\ n";string+="Dexterity:"+ Dexterity +"\ n";string+="Intelligence:"+ Intelligence +"\ n";string+="Items:"; for(Item Item:items) {string+ = item.tostring () +" "; }return string; } }}
LIBGDX JSON file parsing