zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JSON数据转换成Java对象的方法

2023-06-13 09:15:19 时间
第一种方法,使用JSON-lib。
第二种方法,使用JACKSON。
前两种方法,对相对简单的Pojo对象来说,还是比较容易的。但是相对于嵌套多层的数据来说,复杂度就直接上去了。
第三种方法,使用GOOGLE的Gson来解决了。写过安卓的都知道,这东西,是Google出来的,最大的好处就是,基本不依赖其他的包。用起来自然很爽,取值方式非常灵活。对复杂的JSON取值,基本统统搞定。
在Gson中分为两种概念。一个就是JsonObject和JsonArray。具体的看代码
复制代码代码如下:

packagecom.mycompany.gsondata; 
importcom.google.gson.JsonArray; 
importcom.google.gson.JsonObject; 
importcom.google.gson.JsonParser; 

/**
 *Helloworld!
 *
 */ 
publicclassApp{ 

   publicstaticvoidmain(String[]args){ 
       StringjsonData="{\"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\"}]}"; 
       JsonObjectroot=newJsonParser().parse(jsonData).getAsJsonObject(); 
       System.out.println(root.get("questionnaireID").toString());//直接取的根节点值 

       JsonArrayAnswerList=root.getAsJsonArray("answerResults");//取数组 

       for(inti=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()); 
       } 

   } 
}