Google Gson - deserialize list object? (generic type)

前端 未结 13 2293
灰色年华
灰色年华 2020-11-22 09:42

I want to transfer a list object via Google Gson, but I don\'t know how to deserialize generic types.

What I tried after looking at this (BalusC\'s answer):

13条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 10:17

    Refer to example 2 for 'Type' class understanding of Gson.

    Example 1: In this deserilizeResturant we used Employee[] array and get the details

    public static void deserializeResturant(){
    
           String empList ="[{\"name\":\"Ram\",\"empId\":1},{\"name\":\"Surya\",\"empId\":2},{\"name\":\"Prasants\",\"empId\":3}]";
           Gson gson = new Gson();
           Employee[] emp = gson.fromJson(empList, Employee[].class);
           int numberOfElementInJson = emp.length();
           System.out.println("Total JSON Elements" + numberOfElementInJson);
           for(Employee e: emp){
               System.out.println(e.getName());
               System.out.println(e.getEmpId());
           }
       }
    

    Example 2:

    //Above deserilizeResturant used Employee[] array but what if we need to use List
    public static void deserializeResturantUsingList(){
    
        String empList ="[{\"name\":\"Ram\",\"empId\":1},{\"name\":\"Surya\",\"empId\":2},{\"name\":\"Prasants\",\"empId\":3}]";
        Gson gson = new Gson();
    
        // Additionally we need to se the Type then only it accepts List which we sent here empTypeList
        Type empTypeList = new TypeToken>(){}.getType();
    
    
        List emp = gson.fromJson(empList, empTypeList);
        int numberOfElementInJson = emp.size();
        System.out.println("Total JSON Elements" + numberOfElementInJson);
        for(Employee e: emp){
            System.out.println(e.getName());
            System.out.println(e.getEmpId());
        }
    }
    

提交回复
热议问题