使用GSON解释和阅读JSON

时间:2014-02-16 20:49:06

标签: java json gson

我在尝试理解这个JSON字符串时遇到了麻烦。

{
    "results":[
        {
            "user":{
                "gender":"female",
                "name":{
                    "title":"miss",
                    "first":"taylor",
                    "last":"anderson"
                },
                "location":{
                    "street":"3645 dogwood ave",
                    "city":"roseburg",
                    "state":"new hampshire",
                    "zip":"20963"
                },
                "email":"taylor.anderson49@example.com",
                "username":"heavyduck595",
                "password":"liverpool",
                "salt":"UK`o;9a_",
                "md5":"6c8db0305b4591d8d9820d9f8edfd162",
                "sha1":"906df4c09f3a87899666cb57bf974bd9b1950ea6",
                "sha256":"3b12f5e51688578f845bef8ae1750d3e263c2010691010a80ce632a6b2323c03",
                "registered":"1359027425",
                "dob":"16243995",
                "phone":"(934)-888-7068",
                "cell":"(727)-467-8384",
                "SSN":"697-20-6143",
                "picture":"http://api.randomuser.me/0.3/portraits/women/30.jpg"
            },
            "seed":"5eaf02877746c7e",
            "version":"0.3"
        }
    ]
}

这是我第一次真正使用JSON并希望尝试恰当地解释它。这是我到目前为止的代码:

static class Results{
            String results;
        }

        static class User{
            String gender;
            String name;
            String location;
            List<Results> items;
        }


        private static String readUrl(String urlString) throws Exception {
            BufferedReader reader = null;
            try {
                URL url = new URL(urlString);
                reader = new BufferedReader(new InputStreamReader(url.openStream()));
                StringBuffer buffer = new StringBuffer();
                int read;
                char[] chars = new char[1024];
                while ((read = reader.read(chars)) != -1)
                    buffer.append(chars, 0, read); 

                return buffer.toString();
            } finally {
                if (reader != null)
                    reader.close();
            }
        }

        public void larry() throws Exception{
            String json = readUrl("http://api.randomuser.me/");
            System.out.println(json);
            Gson gson = new Gson();        
            User page = gson.fromJson(json, User.class);

            System.out.println(page.name);
            for (Results item : page.items)
              System.out.println("    " + item.results);
        }

1 个答案:

答案 0 :(得分:0)

没有什么特别复杂的JSON,或将其映射到您自己的Java类。你只需要了解基本结构。

您的JSON是一个只有一个字段的对象; results。这就是{}的含义:

{ "results": ... }

该字段包含一个数组。这是[]

{ "results": [ ... ] }

该数组拥有另一个对象(可能你在数组中有多个,但你发布的JSON只有一个)。该对象有三个字段,其中一个(“user”)保存另一个对象,另外两个是字符串。

要将它映射到您自己的类,您只需使它们看起来像JSON:

class JsonResult {
    List<Result> results; // JSON arrays map to Java Lists
}

class Result {
     User user;
     String seed;
     String version;
}

class User {
    String gender;
    Name name;
    // and so on ...
}

class Name {
    String title;
    String first;
    String last;
}

等等。您构建类以匹配JSON中的对象(同样,由{}表示),并相应地构造所有内容。

正如@HotLicks在他的评论中指出的那样,你可以决定不映射到Java类并使用“干净”的解析器。事实上,Gson提供了这个JsonParser课程。这只会将JSON解析为一个树,您可以从中提取所需的信息:

JsonElement element = new JsonParser().parse(yourJsonString);

从那里,您可以使用字段名称访问JSON结构:

JsonObject root = element.getAsJsonObject();
JsonArray array = root.getAsJsonArray("results");

通过访问JSON结构,您可以获得所需的任何内容。