JSON data into Java objects

  • 2020-04-01 03:09:15
  • OfStack

The first is to use json-lib.
The second way is to use JACKSON.
The first two methods are relatively easy for relatively simple Pojo objects. But as opposed to nesting multiple layers of data, the complexity goes straight up.
The third method is solved by using GOOGLE's Gson. As anyone who has written about android knows, this is a Google thing, and the great thing about it is that it doesn't rely on other packages. It's very cool to use, and it's very flexible. For complex JSON values, we're pretty much done.
There are two concepts in Gson. One is JsonObject and JsonArray. See the code specifically

package com.mycompany.gsondata;  
import com.google.gson.JsonArray;  
import com.google.gson.JsonObject;  
import com.google.gson.JsonParser;  

  
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 Fill in the blanks "},{"questionID":"QSTest06","anserContent":"3"},{"questionID":"QSTest07","anserContent":"2.2"}]}";  
        JsonObject root = new JsonParser().parse(jsonData).getAsJsonObject();  
        System.out.println(root.get("questionnaireID").toString());//The value of the root node taken directly & PI;

        JsonArray AnswerList = root.getAsJsonArray("answerResults");//Take an array  

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

    }  
} 

Related articles: