Home  >  Article  >  Java  >  How to convert JSON data into Java objects

How to convert JSON data into Java objects

高洛峰
高洛峰Original
2017-01-19 15:21:101732browse

The first method is to use JSON-lib.
The second method is to use JACKSON.
The first two methods are relatively easy for relatively simple Pojo objects. But compared to nesting multiple layers of data, the complexity goes up directly.
The third method is to use GOOGLE's Gson to solve the problem. Anyone who has written about Android knows that this thing is produced by Google. The biggest advantage is that it basically does not rely on other packages. It's naturally fun to use, and the value setting method is very flexible. For complex JSON values, basically everything is done.
There are two concepts in Gson. One is JsonObject and JsonArray. See the code for details

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

    }  
}

For more related articles on methods of converting JSON data into Java objects, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn