码迷,mamicode.com
首页 > Web开发 > 详细

Libgdx 之JSON文件解析

时间:2016-07-13 17:26:51      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

上一节我们学习了XML文件的解析,接下来我们再了解JSON文件的解析。在Libgdx中也提供了Json类来帮助我们解析文件,最常用的方法是fromJson(java.lang.Class type, FileHandle file) 通过此方法我们必须先定义一个内部类来抽象的表示Json文件。

{
    "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 }
    ]
}

上面的Json文件我们可以看出,Json文件中包含对象name, experience, strength, dexterity, dexterity, intelligence, items, 共7个属性,因此我们需要定义一个Charactor.class类来容纳这7个属性。 同时我们可以知道items包含2个属性: name, number,因此我们需要定义一个类Item.class来容纳这7个属性。
下面是具体的代码实现:

public class JsonTest extends ApplicationAdapter {

    @Override
    public void create() {

        Json json = new Json();
        json.setElementType(Character.class, "items", Item.class);  // 指定Character中的item数据类型
        Character character = json.fromJson(Character.class, Gdx.files.internal("character.json"));    // 从Json文件中创建一个Charactor对象
        System.out.println(character);
//        System.out.println("dexterity: " + character.dexterity);  // 访问单个属性,需要建立对应的class

        System.out.println();

        System.out.println("=====================");
        System.out.println("Serializing character");
        System.out.println("=====================");

        System.out.println(json.prettyPrint(json.toJson(character)));

    }

    public static class Item {
        private String name;
        private int number;

        @Override
        public String toString() {
            return name + "(" + number + ")";
        }
    }

     public static class Character {
            private String name = "";
            private int experience = 0;
            private  int strength = 1;
            private  int dexterity = 1;
            private  int intelligence = 1;

            public Array<Item> items = new Array<Item>();

            @Override
            public String toString() {
                String string = new String();
                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文件解析

标签:

原文地址:http://blog.csdn.net/zqiang_55/article/details/51884239

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!