就目前来说,将Java对象转换成JSON对象仍是至关简单的,可是 将JSON对象转换成Java对象,就相对比较复杂了些。java
第一种方法,使用 JSON-lib 。json
第二种方法,使用 JACKSON。数组
前两种方法,对相对简单的Pojo 对象来讲,仍是比较容易的。可是相对于嵌套多层的数据来讲,复杂度就直接上去了。测试
第三种方法,使用GOOGLE 的Gson 来解决了。写过安卓的都知道,这东西,是Google出来的,最大的好处就是,基本不依赖其余的包。用起来天然很爽,取值方式很是灵活。对复杂的JSON 取值,基本通通搞定。google
在Gson 中分为两种概念。一个就是 JsonObject 和 JsonArray。具体的看代码spa
package com.mycompany.gsondata; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * Hello world! * */ public class App { public static void main(String[] args) { String jsonData = "{\"questionnaireID\": \"QNTest\",\"answerResults\":[{\"questionID\":\"QSTest01\",\"anserContent\":\"cfb7f441-9086-11e3-8cf8-000c2945c442\"},{\"questionID\":\"QSTest01\",\"anserContent\":\"cfb7f441-9086-11e3-8cf8-000c2945c442\"},{\"questionID\":\"QSTest03\",\"anserContent\":\"6b3a9cce-9087-11e3-8cf8-000c2945c442,a086331d-9087-11e3-8cf8-000c2945c442\"},{\"questionID\":\"QSTest01\",\"anserContent\":\"cfb7f441-9086-11e3-8cf8-000c2945c442\"},{\"questionID\":\"QSTest05\",\"anserContent\":\"test测试文字填空\"},{\"questionID\":\"QSTest06\",\"anserContent\":\"3\"},{\"questionID\":\"QSTest07\",\"anserContent\":\"2.2\"}]}"; JsonObject root = new JsonParser().parse(jsonData).getAsJsonObject(); System.out.println(root.get("questionnaireID").toString());//直接取的根节点值 JsonArray AnswerList = root.getAsJsonArray("answerResults");//取数组 for (int i = 0; i < AnswerList.size(); i++) { System.out.println(AnswerList.get(i).getAsJsonObject().get("questionID").toString()); System.out.println(AnswerList.get(i).getAsJsonObject().get("anserContent").toString()); } } }